比方说,我有一个结构:
typedef struct person {
int id;
char *name;
} Person;
为什么我不能执行以下操作:
void function(const char *new_name) {
Person *human;
human->name = malloc(strlen(new_name) + 1);
}
答案 0 :(得分:1)
您需要先为human
分配空间:
Person *human = malloc(sizeof *human);
human->name = malloc(strlen(new_name) + 1);
strcpy(human->name, new_name);
答案 1 :(得分:0)
您必须为结构Person
分配内存。指针应指向为结构分配的内存。只有这样,您才能操纵结构数据字段。
结构Person
包含id,
和char
指针name
到名称。您通常希望为名称分配内存并将数据复制到其中。
在程序结束时,请记住为name
和Person
释放内存。
下达订单很重要。
小样本程序来说明这个概念:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
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.