这是我的代码:
#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);
}
程序在最后一行(push(top, 2);
)的第 3 行出现段错误,我认为就行了top = new_node;
我只是在学习 C(现在的指针)。
我做错什么了?