c - 在结构中填充字符指针

标签 c string pointers struct char

我定义了一个“汽车”结构,其中包含模型 (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/

相关文章:

c - 循环求和给出意想不到的结果

c - 只返回空格和字母的函数

swift - String 子字符串如何在 Swift 中工作

c - 生成的符号名称具有额外的前导下划线

java - 在Java中,我想调用名称为 'foo' 的对象的方法,但 'foo' 是一个字符串。我该如何解决这个问题?

ruby-on-rails - 如何准确查看字符串中的字符?

C++通过其指针和偏移量从类中读取

c - 为什么 "code"与 "name"相同?

c - 在c中生成字指针数组

c - 双重运算每次在C中产生随机数