gpt4 book ai didi

c++节点列表-NULL测试不起作用

转载 作者:行者123 更新时间:2023-11-28 03:58:47 24 4
gpt4 key购买 nike

我想测试以下代码(对于非空列表工作正常),看看在空列表的情况下会发生什么(在这种情况下,头部将为空)。

因此,用于填充列表的代码被注释掉了。

但是由于某些奇怪的原因,在 print_nodes() 中对 NULL 的测试似乎不起作用。我添加了一些调试 cout 调用以查看(并使用 gdb 检查)但是虽然该值确实显示为 NULL,但任何 if 语句似乎都无法正确测试等价性..

知道为什么吗?

非常感谢!

   #include <iostream>
using namespace std;

struct node {
char dat;
node *nextPtr;
};

//inserts new node and returns pointer
node* new_node(char data, node* prevNode);

//adds a new node at the head ofthe list
void new_head (node *head_, char dat_);

//inserts new node after *before
void insert_node (node *before, char dat_);

//runs through and prints the list - requires first node (head)
void print_nodes (node *head);


int main() {
cout <<endl << endl;
cout << endl << "*******************RUN******************" <<endl <<endl;

node* head = NULL;

if (head == NULL) {
cout << "head null"; //this works here
}


//head non-standard
// node* head = new node;
// head->dat ='a';

/*
node* b = new_node('b', head);
node* c = new_node('c', b);
node* d = new_node('d', c);
node* e = new_node('e', d);
node* f = new_node('f', e);

*/
print_nodes(head);

insert_node(head,'N');

print_nodes(head);

cout << endl << "*******************END RUN******************" <<endl;
return 0;
}

node* new_node(char data, node* prevNode) {
node* tempPtr = new node;
tempPtr->dat = data;
tempPtr->nextPtr = NULL; //standard
prevNode->nextPtr = tempPtr;
return tempPtr;
}

void new_head (node *head_, char dat_) {

}

void insert_node (node *before, char dat_) {
node* tempPtr = new node;
tempPtr->dat = dat_;

tempPtr->nextPtr = before->nextPtr;
before->nextPtr = tempPtr;

}


void print_nodes (node *head) {

node* tempPtr = head;

cout << "\nPrinting nodes..." <<endl;

if (tempPtr == NULL) { //this test is not working.. why?
cout << "tempPtr is NULL";
return;
} else { //only run in the non null case
for (tempPtr; tempPtr != NULL; tempPtr = tempPtr->nextPtr) {
cout << "Current node content: " << tempPtr->dat <<endl;
}
}
}

最佳答案

你有一个问题:头没有分配,但插入访问它的“下一个元素”:

before->nextPtr = tempPtr;

head 作为before 传入,您没有为head 分配内存。因此,您在此处取消引用 NULL 指针。

会不会是您的应用程序因此崩溃,并且 cout 的打印输出没有完成,因为 cout 被缓冲了?

尝试:

  1. 删除对 insert 的调用
  2. cout 更改为 cerr(无缓冲)

报告这些变化的结果。

关于c++节点列表-NULL测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1961370/

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