C++ C+中链表节点分配的分段错误+;
我可能又错过了一件很简单的事情,但在实验室里呆了太多的时间,让我看不出我做错了什么。我试图通过创建一个列表并在新字符被读入时向其添加新节点来构建一个从文件读入的所有字符的链接列表,直到文件结束 首先是一些背景知识,下面是节点结构的代码:C++ C+中链表节点分配的分段错误+;,c++,linked-list,segmentation-fault,C++,Linked List,Segmentation Fault,我可能又错过了一件很简单的事情,但在实验室里呆了太多的时间,让我看不出我做错了什么。我试图通过创建一个列表并在新字符被读入时向其添加新节点来构建一个从文件读入的所有字符的链接列表,直到文件结束 首先是一些背景知识,下面是节点结构的代码: typedef struct node { //each node holds a single character char data; //pointer to the next node in the list struct node *next; }no
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);
我不确定它在哪里,但我知道它在那里。如果我能用另一双眼睛指出哪里出了问题,我将不胜感激。您不必在此处初始化
头部
:
node *head, *current = NULL;
因此它将有一个不确定的值,因此该检查很可能失败:
if (head == NULL){
因此,磁头和电流都不能正确初始化
如果使用C++ 11,则应该使用C++而不是<代码> null <代码> .< /P>这是C++理想的,我们应该使用<代码> null pTrp>代码> @ MGEZ理想地,我们不应该使用<代码> FGCTC,<代码> Prtff < /C>,<代码>文件*/COD>,裸指针和冗余<代码>结构> <代码> s。没错!谢谢哇,如果我错过了,也许是时候休息一下了。