C++ c++;节点列表-空测试不工作
我想测试下面的代码(对于非空列表很好),看看在空列表的情况下会发生什么(在这种情况下,head是空的) 因此,用于填写列表的代码被注释掉 但出于某种奇怪的原因,print_nodes()中的NULL测试似乎不起作用。我添加了一些debug cout调用来查看(也使用gdb进行了检查),但是虽然值确实看起来是空的,但是any if语句似乎没有正确地测试等价性 知道为什么吗 非常感谢C++ c++;节点列表-空测试不工作,c++,C++,我想测试下面的代码(对于非空列表很好),看看在空列表的情况下会发生什么(在这种情况下,head是空的) 因此,用于填写列表的代码被注释掉 但出于某种奇怪的原因,print_nodes()中的NULL测试似乎不起作用。我添加了一些debug cout调用来查看(也使用gdb进行了检查),但是虽然值确实看起来是空的,但是any if语句似乎没有正确地测试等价性 知道为什么吗 非常感谢 #include <iostream> using namespace std; struct
#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;
}
}
}
#包括
使用名称空间std;
结构节点{
char-dat;
节点*nextPtr;
};
//插入新节点并返回指针
节点*新节点(字符数据,节点*前置节点);
//在列表的开头添加一个新节点
作废新头(节点*头,字符数据);
//在*之前插入新节点
void insert_节点(节点*之前,字符数据_);
//运行并打印列表-需要第一个节点(头)
无效打印节点(节点*头);
int main(){
cout您有一个问题:头未分配,但insert访问其“下一个元素”:
头
在
之前作为传入,并且您没有为头
分配内存。因此您在此处取消引用空指针
您的应用程序可能因此崩溃,并且由于缓冲了cout
而无法打印到cout
尝试:
删除对插入的调用
将cout
更改为cerr
(无缓冲)
报告这些更改的结果。该代码在windows上使用g++4.4.1对我有效。由于代码中的其他问题,该消息会显示,然后崩溃。您可能看不到该消息,因为崩溃发生在刷新包含该消息的输出缓冲区之前
一般来说,最好将诊断消息写入标准错误(cerr)而不是标准输出,因为错误流没有缓冲。插入前分配磁头:
node * head = new node;
memset(head, 0, sizeof(node));
genius!就是这样!当它在访问打印功能后向我显示分段错误时-毕竟是插入功能-感谢cerr上的提示,将来将使用它。非常感谢!在这些情况下,“genius”在类似情况下会在头撞桌子几次后出现:-)
node * head = new node;
memset(head, 0, sizeof(node));