'Linked list in an element in linked list
I have a program to make a linked list in another linked list/struct.
I have a struct Collection which contains a pointer to the head of a linked list Group. The function add_group, adds another node to the Group linked list. Finally I print my linked list using the print_collection function.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
struct Group {
int id;
int grp_count;
struct Group *next;
};
struct Collection {
int total_count;
struct Group *grp_head;
struct Collection *next;
};
void add_group(int grp_id, int grp_count, struct Collection **);
void print_collection(struct Collection *);
int main() {
struct Collection *p_collection;
//adding grp with id as 1 and grp_count 5
add_group(1, 5, &p_collection);
add_group(2, 7, &p_collection);
add_group(3, 4, &p_collection);
print_collection(p_collection);
}
void add_group(int grp_id, int grp_count, struct Collection **addr_p_collection) {
//making new group
struct Group *newGroup;
newGroup = (struct Group *)malloc(sizeof(struct Group));
newGroup->id = grp_id;
newGroup->grp_count = grp_count;
newGroup->next = NULL;
//adding grp to collection
//making new Collection if it doesn't exist
if (*addr_p_collection == NULL) {
*addr_p_collection = (struct Collection *)malloc(sizeof(struct Collection));
(*addr_p_collection)->total_count = grp_count;
(*addr_p_collection)->grp_head = newGroup;
(*addr_p_collection)->next = NULL;
return;
} else {
(*addr_p_collection)->total_count += grp_count;
struct Group * tempGroup = (*addr_p_collection)->grp_head;
while (tempGroup->next != NULL) {
tempGroup = tempGroup->next;
}
tempGroup->next = newGroup;
}
};
void print_groups(struct Group *groups_list) {
struct Group *temp = groups_list;
while (temp != NULL) {
printf("Id: %d\tGroup Count: %d\n", temp->id, temp->grp_count);
temp = temp->next;
}
printf("\n");
};
void print_collection(struct Collection * p_collection){
struct Collection *temp = p_collection;
while (temp != NULL) {
printf("Total: %d\n", temp->total_count);
print_groups(temp->grp_head);
temp = temp->next;
}
};
Why does compiling this program in cs50 IDE with gcc command shows segmentation fault, but compiles using make command?
Output:
~/sem2/assign-2/ $ make d
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow d.c -lcrypt -lcs50 -lm -o d
~/sem2/assign-2/ $ ./d
Total: 16
Id: 1 Group Count: 5
Id: 2 Group Count: 7
Id: 3 Group Count: 4
~/sem2/assign-2/ $ gcc d.c
~/sem2/assign-2/ $ ./a.out
Segmentation fault
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
