2009-12-19 66 views
0

我有一個名爲表結構,我只是想創建一個表,就像在java的構造函數,但是當我調用主這個功能,它提供了分段故障ç分割斷裂構造

struct table *create(char *name,int number,char *s_name) 
{ 
    struct table *newTable; 
    newTable->name = name; 
    newTable->number = number; 
    newTable->s_name = s_name; 
    return newTable; 
} 

回答

10
struct table *newTable = malloc(sizeof(struct table)); 

不要忘記調用free,當你用它做,因爲C沒有一個垃圾收集器像Java了。

+1

這應該是'sizeof(struct table)'或'sizeof * newTable'(我更喜歡後者)。與C++不同,struct標籤必須以'struct'關鍵字開頭。 – 2009-12-21 14:30:50

+0

@John:除非table是typedeffed ...我仍然編輯它。 – 2009-12-21 14:52:04

8

你的天堂」爲該對象分配任何內存,並且正在取消引用該結構的字段。您需要訪問之前使用malloc爲newtable的分配內存它

0

您正在嘗試訪問未分配/未初始化的內存& SIGSEGV(分段錯誤)對於代碼來說非常合適,除非您使用malloc或其他內存分配方法明確分配內存。

0

嘗試:

struct table *create(char *name,int number,char *s_name) 
{ 
    struct table *newTable = malloc(sizeof(*newTable)); 
    if (!newTable) 
    return NULL; 

    newTable->name = name; 
    newTable->number = number; 
    newTable->s_name = s_name; 
    return newTable; 
} 

謹慎的另一個詞:在這段代碼中,newTable->name只是指向提供name,無副本。這可能不是你想要的,但是很難從這個小片段中看出來。另一種方法是複製名稱。 s_name也是如此。

+0

使用strdup()爲eliben提到的名稱和s_name做到這一點。指定他們是一個禁忌。 – t0mm13b 2009-12-21 14:55:20