Here’s my code:
#include <stdio.h>
typedef struct node_struct {
int data;
struct node_struct *next;
} node;
void push(node *top, int data) {
node *new_node = (node*) malloc(sizeof(node));
new_node->data = data;
new_node->next = top;
top = new_node;
}
int main() {
node *top = (node*) malloc(sizeof(node));
top->data = 1;
printf("Set data of top node to: %d\n", top->data);
push(top, 2);
printf("Pushed 2 to top, top->next->data = %d\n", top->next->data);
}
The program segfaults at the 3rd last line (push(top, 2);) and I think on the line top = new_node;
I’m just learning C (pointers right now).
What did I do wrong?
The problem here is that you pass the pointer to the
topelement by-value, and then you try to set the pointer inside the function but there it’s just a local variable and changes to it will not be visible outside of the function.Pass the
toppointer by reference instead, by using a pointer to the pointer:An alternative is to return the new top from the function instead: