C++ 为什么在声明节点以创建链接列表时静态内存分配不起作用 #包括 使用名称空间std; 结构节点{ int数据; 节点*下一步; 节点(){} 节点(int数据){ 这->数据=数据; 此->下一步=空; } }; 节点*createlinklist(){ 节点*头=新节点(); int数据; coutnext=NULL; } 节点*it=头部; cin>>数据; while(数据!=-1){ 节点*温度; 温度->数据=数据; temp->next=NULL; it->next=temp; it=it->next; cin>>数据; } 回流头; } 无效打印(节点*头){ while(head!=NULL){ 第一点,它被称为自动分配,而不是静态分配
第二点,此代码是未定义的行为,因为它使用非斜体指针C++ 为什么在声明节点以创建链接列表时静态内存分配不起作用 #包括 使用名称空间std; 结构节点{ int数据; 节点*下一步; 节点(){} 节点(int数据){ 这->数据=数据; 此->下一步=空; } }; 节点*createlinklist(){ 节点*头=新节点(); int数据; coutnext=NULL; } 节点*it=头部; cin>>数据; while(数据!=-1){ 节点*温度; 温度->数据=数据; temp->next=NULL; it->next=temp; it=it->next; cin>>数据; } 回流头; } 无效打印(节点*头){ while(head!=NULL){ 第一点,它被称为自动分配,而不是静态分配,c++,list,function,C++,List,Function,第二点,此代码是未定义的行为,因为它使用非斜体指针 #include <iostream> using namespace std; struct node{ int data; node* next; node(){} node(int data){ this->data=data; this->next=NULL; } }; node* createlinklist(){ node*he
#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
一个值,因此像这样使用temp->data
是一个错误。这与分配类型无关。问题是,无论如何,temp
都没有被分配到任何指向的值
第三点,让我们尝试用自动分配来解决上述问题,您可以编写此代码并编译它
while (data != -1) {
node* temp;
temp->data = data;
temp->next = NULL;
it->next = temp;
it = it->next;
cin>>data;
}
此代码在运行时很可能会崩溃。原因是正在使用函数外部的
auto_节点
对象。这可能是您真正的误解。虽然您没有直接使用auto_节点
对象,但您保留了指向这些对象的指针,即所有下一个
指针链接列表中的指向这些自动分配的节点,这些节点不存在于createlinklist
函数之外。node*temp;temp->data=data;
是未定义的行为。temp
是未分配的垃圾,不指向任何东西。node*temp;
是指针。如果它们不指向有效对象(或可在测试中使用的安全驻车值,如nullptr
)。您必须以这种或那种方式提供该对象,动态分配是这里最有意义的方式。关键是您没有任何静态分配的节点。node*temp;
是指针,而不是节点。读取。学习使用和调试程序。编译时启用所有警告和调试信息(在Linux上,使用g++-Wall-Wextra-g
)PS虽然我知道你的意思,但是你混淆了术语,你所说的静态分配实际上是自动分配。静态意味着其他东西。
while (data != -1) {
node auto_node;
node* temp = &auto_node; // a pointer to an automatically allocated object
temp->data = data;
temp->next = NULL;
it->next = temp;
it = it->next;
cin>>data;
}