【发布时间】:2021-08-03 07:28:30
【问题描述】:
假设我定义了一个结构,其中包含指向对象的指针数组,如下所示:
struct node {
node *arr[10];
};
然后,我在堆上初始化结构的一个实例并检查其指针数组的内容。
node *curr = new node;
for (int i = 0; i < 10; ++i) {
if (curr->arr[i] == nullptr) std::cout << "null" << std::endl;
} // this would print "null" 10 times in my tests in online IDEs and on QTCreator's C++ environment.
但是,为什么我看到数组的每个元素都是 nullptr?它不应该是一个垃圾值吗?这是所有带有指针数组的结构的默认行为吗?
我认为它们应该只是垃圾指针,而不是所有空指针。关于如何考虑初始化node 实例的任何提示都很棒!谢谢!
【问题讨论】:
-
“垃圾”的真正意思是“不确定的”——它们可能碰巧是空指针。 (确实,许多操作系统在首次将内存提供给进程时会将其归零,因此 如果 您从操作系统获取新内存,而不是从以前的
delete重用内存,您将 更多可能会看到零。绝不保证!) -
stackoverflow.com/questions/35666894/garbage-characters-in-c/… 解释的很好——对于字符,不是指针,但是原理是完全一样的。
标签: c++ pointers struct initialization