I've just started out with C and I think the whole pointers/malloc/free is driving me mad. I tried to define a simple linear recursive data structure and loop through it, printing each element that I've looped through. (Code as below).
However, I'm getting Segmentation Fault: 11 as soon as I try to move to the next element to "insert" a new element
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct number_list {
int num;
struct number_list *next_num;
} numlist;
int main() {
numlist *cur, *pointer;
numlist *NewList=NULL;
cur = NewList;
cur = malloc(sizeof(numlist));
cur->num=5; // this operation is never reached too
cur = cur->next_num // Must I malloc?
printf("Reached."); // Is never reached.
cur->num=9;
pointer=NewList;
while (pointer!=NULL) {
printf("%d", pointer->num);
pointer=pointer->next_num;
}
return 0;
}
Furthermore, I have on another larger program a while-loop that functions exactly like this while-loop here except on a "filled" recursive structure. Hence I don't actually need to create any new element, just run through and print each element out. However, in that moment where the loop prints the last element, it crashes with Segmentation Fault: 11 again. I'm guessing it's likely because I tried to do pointer = pointer->next_num
. How do I then correctly run through such a data structure correctly on C anyway?