请考虑以下代码:
#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
那么创建指针并为其分配内存的正确方法是什么?