请帮我解决这个意想不到的输出

时间:2015-07-14 17:29:22

标签: c++ linked-list

这是我的链接列表的示例C ++代码。这实际上不是一个链表而只是一个虚拟程序。我得到了这个程序的意外输出。

#include<iostream>
using namespace std;

struct list{
int data;
list *next;
};

void setData(list ob){
    int d;
    cout<<"enter data"<<endl;
    cin>>d;
    ob.data=d;
}

void getData(list ob){
    cout<<"Data is :"<<ob.data<<endl;
}


int main(){
list node1,node2,node3;
setData(node1);
setData(node2);
setData(node2);
getData(node1);
getData(node2);
getData(node3);

    return 0;

}

我对代码的输入是2,3和4.我得到的意外输出是 -

enter data
2
enter data
3
enter data
4
Data is :2293540
Data is :4201920
Data is :2293608

修改

struct list{
 char data; list next; 
} 
void main(){
 list *start,node1,node2; 
//I got stuck on the below two lines 
start=(struct list)malloc(sizeof(list)); //Dynamic allocation of memory of size list whose address is stored in start
 start=&node1; // start holds the address of node1 which is not dynamically allocated .

我不明白为什么*如果第二个语句通过给它堆栈中的node1的内存地址(我理解的那个)来覆盖它,为什么* start会给出一个动态地址。

2 个答案:

答案 0 :(得分:6)

因为您按值传递链接列表。要更改此内容,请通过引用传递。

void setData(list& ob){
    int d;
    cout<<"enter data"<<endl;
    cin>>d;
    ob.data=d;

当您通过值传递时,C ++会对传入的任何内容进行复制。因此,当您调用getData时,会传入一个没有数据的列表副本它,所以垃圾被打印出来。

答案 1 :(得分:3)

您需要通过引用传递list

void setData(list& ob){
    int d;
    cout<<"enter data"<<endl;
    cin>>d;
    ob.data=d;
}

您目前正在通过传递ob,因此尽管您确实正确设置了data属性,但您正在对函数进行本地操作复制ob,而不是您传入函数的原始list