2013-03-11 91 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)結束。