문제

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

I meant to use the data inside item, but I get a Segmentation Fault on the line:

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

I'm fairly new to C and pointers, but I can't find the problem here.

도움이 되었습니까?

해결책 2

Put this after allocating memory for x:

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

You have to allocate the memory for the field 'item' before you can actually access and allocate its fields.

다른 팁

You haven't allocated memory for the structure pointed to by x->item. Add

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

before the other malloc.

This should do just fine:

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top