我只是尝试使用malloc,代码运行良好,但是Visual Studio却给我带来了问题。这是您应该怎么做的事情,还是我做错了事?
警告直接出现在行上:
chadley->name = "chadley"
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int age;
char *name;
} Person;
int main()
{
Person bradley;
bradley.name = "bradley";
bradley.age = 2334444;
Person *chadley = malloc(sizeof(Person));
chadley->name = "chadley";
chadley->age = 234;
printf("Person object %s of age %d", chadley->name, chadley->age);
}
错误代码:取消引用NULL指针“查德利”
答案 0 :(得分:3)
Person *
可以为空指针。它是指值,而不是类型。
如果无法成功分配内存,则malloc
将返回一个NULL
值。使用前,应始终检查从malloc
返回的值。
您可以执行以下操作来检查返回的指针是否有效:
Person *chadley = malloc(sizeof(Person));
if (!chadley) {
/* The allocation failed, don't continue. */
return 1;
}
chadley->name = "chadley";
chadley->age = 234;
答案 1 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int age;
char *name;
} Person;
int main()
{
Person bradley;
bradley.name = "bradley";
bradley.age = 2334444;
Person *chadley = malloc(sizeof(Person));
if (chadley == NULL) return 1;
chadley->name = "chadley";
chadley->age = 234;
printf("Person object %s of age %d", chadley->name, chadley->age);
}
工程谢谢!