Reputation: 157
I'm learning how to implement linked lists in C. I understand the basics of normal linked lists, how to add values, how to print them etc. but I've been wondering - is it possible to add other structure as a value in linked list? What I mean is:
typedef struct personal_info {
char *name;
char *surname;
int phone_number;
} Info;
typedef struct llist {
Info *info;
struct llist *next;
} List;
And when I do this, how do I access the values of the Info
structure?
List *l;
l = malloc(sizeof(List));
l->info->name = 'name';
l->info->surname = 'surname';
l->info->phone_number = 1234567890;
The code crashes, so I'm definitely doing something wrong. Could you give me some tips how to achieve that?
Upvotes: 1
Views: 5362
Reputation: 26251
You also need to allocate memory for the info struct:
l = malloc(sizeof(List));
l->info = malloc(sizeof(Info));
l->info->name = "name";
l->info->surname = "surname";
l->info->phone_number = 1234567890;
Upvotes: 4
Reputation: 76888
List *l;
l = malloc(sizeof(List));
l->info = malloc(sizeof(Info));
You have to malloc memory for the struct as well
Also remember that if you're implementing any functions that remove nodes from the list, you need to free that struct before you free the node.
Upvotes: 4