这个奇怪的数字在输出中是什么意思?这是一些内存位置吗?



节点类如下:

class node
{
public:
int data; //the datum
node *next; //a pointer pointing to node data type
};

PrintList函数如下:

void PrintList(node *n)
{   while (n != NULL)
{
cout << n->data << endl;
n = n->next;
}
}

如果我试着运行它,我得到所有三个值(1,2,3),但我得到一个额外的数字,以及我无法弄清楚它代表什么,有人能扔光在相同的?

int main()
{
node first, second, third;
node *head = &first;
node *tail = &third;
first.data = 1;
first.next = &second;
second.data = 2;
second.next = &third;
third.data = 3;
PrintList(head);    
}

我知道它可以用

修复
third.next = NULL;

但是我只是好奇这个数字在输出中表示什么,如果我省略上面的行

1
2
3
1963060099

如prapin注释所述,third.next未初始化。c++有一个零开销规则。自动初始化变量将违反此规则,因为该值可能稍后被初始化(第二次),或者甚至永远不会被使用。

third.next的值恰好是与third.next现在位于相同内存位置的数据。因此,建议始终自己初始化变量。

最好初始化变量&最好使用nullptr。像这样(见1-3):

#include <iostream>
class node
{
public:
int data = 0; // 1
node* next = nullptr; // 2
};
void PrintList(node* n)
{
while (n != nullptr) // 3
{
std::cout << n->data << std::endl;
n = n->next;
}
}

int main()
{
node first, second, third;
node* head = &first;
node* tail = &third;
first.data = 1;
first.next = &second;
second.data = 2;
second.next = &third;
third.data = 3;
// third.next points to where?
PrintList(head);
}

额外注意:

我更喜欢使用STL容器std::list:

#include <list>
#include <iostream>
std::list<int> int_list;
void PrintList()
{
for (auto i : int_list)
std::cout << i << std::endl;
}
int main()
{
int_list.push_back(1);
int_list.push_back(2);
int_list.push_back(3);
PrintList();
}

对于node对象列表:

#include <list>
#include <iostream>
class node
{
public:
node(int data) : m_data{ data } {};
int m_data = 0;
// and maybe extra data-members
};
std::list<node> node_list;

void PrintList()
{
for (auto i : node_list)
std::cout << i.m_data << std::endl;
}   
int main()
{
node_list.push_back(node(1));
node_list.push_back(node(2));
node_list.push_back(node(3));
PrintList();
}