gpt4 book ai didi

c - 除非我在其他所有内容之前添加 printf,否则我的 C 程序无法运行

转载 作者:行者123 更新时间:2023-11-30 14:34:58 24 4
gpt4 key购买 nike

我尝试运行代码,它终止并且不打印任何内容,但如果我在主代码的第一行包含 printf 语句,它就会起作用。为什么?

#include <stdio.h>
#include <stdlib.h>

typedef struct node TNode;
typedef struct list TList;

struct list{
TNode *node;
};

struct node{
int data;
TNode *next;
};

TList* buildList(){
TList *list;
list = (TList*)malloc(sizeof(TList));
list->node->next = NULL;
printf("\nList was built successfully\n");
return list;
}


int main(){
TList *myList = buildList();
myList->node->data = 5;
printf("\nData: %d\n", myList->node->data);
return 0;
}

最佳答案

您正在访问list->node->next,但尚未初始化list->node。为节点分配内存,并将指向该节点的指针分配给list->node

#include <stdio.h>
#include <stdlib.h>

typedef struct node TNode;
typedef struct list TList;

struct list{
TNode *node;
};

struct node{
int data;
TNode *next;
};

TList* buildList(){
TList *list;
list = (TList*)malloc(sizeof(TList));
list->node = (TNode*)malloc(sizeof(TNode)); // <---
list->node->next = NULL;
printf("\nList was built successfully\n");
return list;
}


int main(){
TList *myList = buildList();
myList->node->data = 5;
printf("\nData: %d\n", myList->node->data);
return 0;
}

关于c - 除非我在其他所有内容之前添加 printf,否则我的 C 程序无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759962/

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