在结构中填充char指针

kyl*_*yle 8 c string struct pointers char

我已经定义了一个带有模型(char*模型)和模型年份(int year)的"car"结构.我有一个功能,将创建一个新的汽车结构; 但是,复制char指针时会出现seg faulting.这应该为链表创建一个新节点.

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;
}
Run Code Online (Sandbox Code Playgroud)

kyl*_*yle 5

供将来参考,此功能解决了我的问题...

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;
}
Run Code Online (Sandbox Code Playgroud)