請考慮下面的代碼:爲什麼malloc不無鑄造工作?
#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
那麼,什麼是創建一個指針和內存分配給它一個適當的方式?
如果你寫C代碼,你應該總是** **編譯C和你**絕不**投的malloc'的返回值()'。 – 2012-12-21 17:36:55
重命名'struct.cpp'爲'struct.c'使Visual Studio中挖掘其令人難以置信的過時的C編譯器。 – Cubbi
BTW,不要'assert'的返回值'malloc'。用if語句檢查它的返回值。 – netcoder