2009-12-19 121 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