gpt4 book ai didi

c - 指针赋值无效

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:34 27 4
gpt4 key购买 nike

#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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com