次のコードを検討してください:
#include "stdafx.h"
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight)
{
struct Person *who = (struct Person*) malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
気になるラインは
struct Person *who = (struct Person*) malloc(sizeof(struct Person));
malloc() の使用法についてインターネットで少し検索しました。それらの約半分はキャストで書かれており、残りはそうではありません。vs2010 では、(struct Person*)
キャストせずにエラーが発生します。
1>c:\users\juhyunlove\documents\visual studio 2010\projects\learnc\struct\struct\struct.cpp(19): error C2440: 'initializing' : cannot convert from 'void *' to 'Person *'
1> Conversion from 'void*' to pointer to non-'void' requires an explicit cast
それでは、ポインタを作成してそれにメモリを割り当てる適切な方法は何でしょうか?