C:访问结构中的结构

时间:2014-05-09 22:22:09

标签: c pointers structure

typedef struct mensagem
{
    int sender ;
    int receiver ;
    char *text ;
} *Item ;


typedef struct node 
{
    Item item ;
    struct node *next ;
} *link ;

link init(char* text)
{
    link x = (link) malloc(sizeof(struct node));
    (x->item->text) = (char*) malloc(sizeof(char)*(strlen(text)+1));
    strcpy(x->item->text, text);
    x->next = NULL;
    return x;
}

我打算使用item中的数据,但是我在行上得到了Segmentation Fault:

(x->item->text) = (char*) malloc(sizeof(char)*(strlen(text)+1));

我对C和指针都很陌生,但我无法在这里找到问题。

3 个答案:

答案 0 :(得分:1)

您还没有为x-> item指向的结构分配内存。添加

x->item = malloc(sizeof (struct mensamam));

在另一个malloc之前。

答案 1 :(得分:0)

在为x:

分配内存之后输入
x->item = malloc(sizeof(struct mensagem));

你必须为字段' item'分配内存。在您实际访问和分配其字段之前。

答案 2 :(得分:0)

这应该没问题:

typedef struct mensagem
{
    int sender ;
    int receiver ;
    char *text ;
} Item ;


typedef struct node 
{
    Item *item ;
    struct node *next ;
} Link ;

Link *init(char *text)
{
    // Note: Do error checking after each of these lines in case malloc() fails!
    Link *x = malloc(sizeof(Link));
    x->item = malloc(sizeof(Item));
    x->item->text = malloc(sizeof(char) * (strlen(text) + 1));

    strcpy(x->item->text, text);
    x->next = NULL;
    return x;
}