我定义了一个“汽车”结构,其中包含模型 (char *model) 和模型年份 (int year)。我有一个函数可以创建一个新的汽车结构;但是,复制 char 指针时会出现段错误。这应该为链表创建一个新节点。
Car *newCar(char *model, int year){
Car *new = malloc(sizeof(Car));
new->year = year;
new->model = malloc(MAX_LENGTH*sizeof(char));
strcpy(new->model, model);
new->next = NULL;
return new;
}
最佳答案
为了将来引用,此功能解决了我的问题...
Car *createCar(char *model, int year){
Car *new = malloc(sizeof(Car));
new->year = year;
new->model = malloc(strlen(model)+1);
strcpy(new->model, model);
new->next = NULL;
return new;
}
关于c - 在结构中填充字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15332541/