gpt4 book ai didi

c++ - C++中链表节点分配的段错误

转载 作者:行者123 更新时间:2023-11-30 02:51:54 25 4
gpt4 key购买 nike

我可能又遗漏了一些非常简单的东西,但在实验室中花费了太多时间,以至于我看不出我在这里做错了什么。我试图通过创建一个列表并在读入新字符时向其附加新节点来构建从文件中读入的所有字符的链表,直到文件末尾。

首先是一些背景,这里是节点结构的代码:

typedef struct node
{
//each node holds a single character
char data;
//pointer to the next node in the list
struct node *next;
}node;

通过使用几个 printf 语句,我设法将问题缩小到这段代码中的某处。

FILE *infile = fopen("data.txt", "r");

int c;
int counter = 0;
node *head, *current = NULL;

//Get the count of our original rules and create the list
do{

node *item = new node();

c = fgetc(infile);

if(c == '\n'){
counter ++;
}

printf("From infile: %c \n", c);

item->data = c;
item->next = NULL;

printf("Item data: %c", item->data);

if (head == NULL){
head = current = item;
}
else {
current->next = item;
current = item;
}

}while( c != EOF);

我不确定它在哪里,但我知道它在那里。如果我能让另一双眼睛指出哪里出了问题,我将不胜感激。

最佳答案

你不要在这里初始化head:

node *head, *current = NULL;

所以它会有一个不确定的值,所以很可能这个检查失败了:

if (head == NULL){

因此 headcurrent 都不会被正确初始化。

如果你使用的是 C++11 那么你应该使用 nullptr而不是 NULL

关于c++ - C++中链表节点分配的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19389225/

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