为什么我不能动态分配这个结构字符串的内存?

比方说,我有一个结构:

typedef struct person { int id; char *name; } Person; 

为什么我不能做以下事情:

 void function(const char *new_name) { Person *human; human->name = malloc(strlen(new_name) + 1); } 

你需要先为human分配空间:

 Person *human = malloc(sizeof *human); human->name = malloc(strlen(new_name) + 1); strcpy(human->name, new_name); 

您必须为结构Person分配内存。 指针应指向为结构分配的内存。 只有这样,您才能操纵结构数据字段。

结构Person拥有id,并且char指针name为name。 您通常希望为名称分配内存并将数据复制到其中。 在程序结束时记得为namePerson释放内存。 下达订单很重要。

提供了用于说明概念的小样本程序:

 #include  #include  #include  typedef struct person { int id; char *name; } Person; Person * create_human(const char *new_name, int id) { Person *human = malloc(sizeof(Person)); // memory for the human human->name = malloc(strlen(new_name) + 1); // memory for the string strcpy(human->name, new_name); // copy the name human->id = id; // assign the id return human; } int main() { Person *human = create_human("John Smith", 666); printf("Human= %s, with id= %d.\n", human->name, human->id); // Do not forget to free his name and human free(human->name); free(human); return 0; } 

输出:

 Human= John Smith, with id= 666.