【发布时间】:2019-02-24 07:26:33
【问题描述】:
#include <iostream>
using namespace std;
struct node{
int data;
node* next;
node(){}
node(int data){
this->data=data;
this->next=NULL;
}
};
node* createlinklist(){
node*head=new node();
int data;
cout<<"Enter data and -1 to exit"<<endl;
cin>>data;
if(data!=-1){
head->data=data;
head->next=NULL;
}
node* it=head;
cin>>data;
while(data!=-1){
node* temp;
temp->data=data;
temp->next=NULL;
it->next=temp;
it=it->next;
cin>>data;
}
return head;
}
void print(node* head){
while(head!=NULL){
cout<<head->data<<"-->";
head=head->next;
}
cout<<"NULL"<<endl;
}
对于上面的代码,当我为 temp 动态分配内存并执行 node* temp=new node();链接列表打印完美,但是当我以发布代码的方式执行上述操作时,它在第一个节点之后就不起作用了。从我所有的研究来看,在这种情况下,动态分配似乎根本不应该有所作为,对吧?我没有使用超出函数范围的静态分配节点,所以我不明白为什么如果我不使用动态分配临时它不会打印。
【问题讨论】:
-
node* temp; temp->data = data;是未定义的行为。temp是未分配的垃圾,没有指向任何东西。 -
node* temp;是一个指针。如果指针不指向有效对象(或可在测试中使用的安全停放值,如nullptr),则指针将毫无用处。您必须以一种或另一种方式提供该对象,而动态分配是这里最有意义的方式。 -
关键是你没有任何静态分配的节点。
node* temp;是指针,不是节点。 -
阅读How to debug small programs。学习使用valgrind 和gdb 调试器。编译时启用所有警告和调试信息(在 Linux 上,使用
g++ -Wall -Wextra -g) -
PS 虽然我知道你的意思,但你混淆了术语,你所说的静态分配,实际上是自动分配。静态意味着别的东西。