I've been learning programming for some while now and I've seen this concept of "linked list" a few times and decided to give it a try:
#include <stdio.h>
#include <stdlib.h>
typedef struct cell {
int number;
struct cell* next;
} cell;
typedef struct {
cell* head;
} cell_list;
void push_front(cell_list* list, int number) {
printf("here\n");
cell* n;
printf("here2\n");
n->number = number;
printf("here3\n");
n->next = list->head;
printf("here4\n");
list->head = n;
}
int main(int argc, char* argv[]) {
cell_list* L;
push_front(L, 5);
push_front(L, 8);
push_front(L, 19);
cell* n = L->head;
// this should print "19 8 5"
while(n != NULL) {
printf("Val: %d\n", n->number);
n = n->next;
}
return 0;
}
output:
here
here2
here3
Segmentation fault: 11
I am looking for an answer to the following two questions: (1) What is the correct way of doing this (2) What is actually happening in my example? What is going wrong?
I am thinking that it is the compiler that fails to assign "struct cell* next" to be equal to "cell* head", etc.) OR that the FIRST allocated memory for head and the fist cell with the next property is at fault here.
Also similar posts and questions have answer to questions identical to mine however they fail at multiple points: (1) the code example posted by OP is overly complex (2) the code answers are good but... check 3 (3) the code answers and not explained, just "omg just use malloc you are casting voids everywhere" (4) 1 - 3 results in a complete post with Q&A that is above my level. If your answer is "use malloc" or "the pointers point at random memory" or "you are pointing at null". Please explain because these are just programming jargon/language sentences that don't actually go into depth so that I, a beginner, can understand.
I am fully aware there are identical posts but none truly explain to a beginner like me why they allocate memory will malloc and cast the allocated space to become a linked list struct. If your answer is the same as in any of those posts, then please explain why this way is faulty and not just "This is how you do, there are 12893 posts about malloc and linked lists." I understand malloc and casting if that was not obvious but not how they properly fit in here and how my current program is created on the stack.