c -在结构体中填充char指针



我定义了一个带有模型(char *model)和模型年份(int year)的"car"结构体。我有一个函数来创建一个新的car结构体;但是,在复制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;
}

这里你的模型是字符指针。

但是strp需要两个参数-应该是arraycharacter pointer to which memory allocated by malloc or calloc

但是你的strcpy();有一个参数作为字符指针,这是不被接受的

所以要

new->model = malloc(strlen(model) + 1),然后写你的strcpy (),它将工作

你可以试试:

new->model = model == NULL ? NULL : strdup(model);

这可以防止你从一个错误,如果模型是NULL,否则malloc你的空间的确切数量和strcopy;此外,这允许您在所有情况下在结尾处设置free(new->model)

看看下面的代码,并将其与你的程序进行比较,我相信你会发现你的程序出了什么问题

#include <stdio.h>
#include <string.h>
typedef struct car{
char *model;
int year;
}Car;
Car * newCar(char *, int );
int main()
{
Car *benz = newCar("S-class",1990);
printf("nModel = %sn",benz->model);
printf("nYear = %dn",benz->year);
}
Car * newCar(char *model, int year)
{
    Car *new = malloc(sizeof(Car));
    new->year = year;
    new->model = malloc(strlen(model));
    strcpy(new->model, model);
    return new;
}

最新更新