SimCity
SimCity

Reputation: 549

How to initialize a structure within a structure in C?

I have these two structures :

struct member {
  char *nickname;
  char *group;
};

struct node {
   struct member mbr;
   struct node   *next;
};

Further in my code I do this :

struct node* n = (struct node*)malloc(sizeof(struct node));

And get a "Segmentation fault" error at this line when I run the program :

strcopy(n->mbr.nickname, temp->nickname);

I've been trying for a while to solve this problem and I've searched on the web, but I didn't find any solution yet. I'm guessing the structure inside 'n' isn't initialized. I did a few test that looked like :

n->mbr = (struct member*)malloc(sizeof(struct member));

But then I get another error : "incompatible types when assigning to type 'struct member' from type 'struct member *'"...

Can anyone tell me what I'm doing wrong? Thanks.

Upvotes: 0

Views: 269

Answers (1)

Ry-
Ry-

Reputation: 225238

You don’t need to allocate mbr; you need to allocate mbr.nickname.

struct node* n = malloc(sizeof (struct node));
n->mbr.nickname = malloc(some number of characters);

Then use strncpy. Alternatively,

n->mbr.nickname = strdup(temp->nickname);

which is the same as doing that, but using strlen(temp->nickname) + 1 as the size.

Upvotes: 2

Related Questions