#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node * next;
} node;
int main()
{
node * head;
head->data=5; //crash
}
我不明白为什么这样的东西会崩溃?几个月来我一直在使用指针,但最简单的例子似乎让我感到困惑。
最佳答案
扩展 juanchopanza 在评论中所说的内容:
您的 node * head;
创建了一个指针,但它不指向任何有效的 node
结构。
您首先需要使用 malloc
为其分配空间,例如:
node * head = malloc(sizeof(node));
另外不要忘记在程序结束时free
,以免造成内存泄漏:
自由(头部);
关于c - 指针赋值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26441262/