2013-03-11 56 views
6

我已经用模型(char *模型)和模型的年份(int年)定义了“car”结构。我有一个功能,将创建一个新的汽车结构;然而,复制char指针时会出现seg错误。这应该为链表创建一个新节点。在结构中填充字符指针

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; 
} 
+0

怎么样'新建 - >模式=的malloc(strlen的(模型)+ 1)'? – cnicutar 2013-03-11 06:39:25

+4

你应该检查'char * model'不是'NULL'。此外,作为良好的做法,总是检查'malloc's的返回。 – congusbongus 2013-03-11 06:39:41

+0

@cnicutar谢谢;然而,问题仍然存在。 – kyle 2013-03-11 06:41:22

回答

2

以供将来参考此功能固定我的问题......

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; 
} 
+1

你malloc'd错误的空间量。它应该是'strlen(model)+ 1'。如果这似乎解决了你的问题,你一直在蛋壳上行走! – 2015-11-02 22:33:12

+0

@ M.M你是对的!我从一年级开始完成旧作业,并意识到我从未发布过解决方案。我已经更新了我的答案,以反映您发现的错误。 – kyle 2015-11-02 22:48:05

3

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

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

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

所以请

new->model = malloc(strlen(model) + 1),然后写你的strcpy ()它会奏效。

+1

或'new-> model = strdup(model);'同一个单一指令。 – 2013-03-11 10:29:22

+1

@EdouardThiel除了'strdup'不是标准的(尽管它很容易实现)。 – cnicutar 2013-03-11 16:02:25

+0

strdup()符合SVr4,4.3BSD,POSIX.1-2001。 – 2013-03-16 13:36:57

1

看一看下面的代码,并将其与你的程序比较,相信你会发现什么是错了你的程序

#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 = %s\n",benz->model); 
printf("\nYear = %d\n",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; 
} 
4

你可以试试这个:

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

这样可防止如果你的模型为NULL,那么你从bug中得到一个错误,否则malloc会得到精确的空间量并且strcopy它;再加上,这可以让你在所有情况下都以free(new->model)结束。