gpt4 book ai didi

c++ - 了解 C++ 中的零和 NULL

转载 作者:行者123 更新时间:2023-11-28 05:55:28 26 4
gpt4 key购买 nike

在寻找我应该使用 Zero 还是 Null 的答案时,我在 another question 中找到了这个答案来自用户 stroustup 的 SO:

Should I use NULL or 0? In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

所以 NULL 和 0 是一样的,这很酷。但我需要在这里多一点理解:假设我有以下内容(来自 cprogramming.com 的随机示例):

struct node {
int x;
node *next;
};

int main()
{
node *root; // This won't change, or we would lose the list in memory
node *conductor; // This will point to each node as it traverses the list

root = new node; // Sets it to actually point to something
root->next = 0; // Otherwise it would not work well
root->x = 12;
conductor = root; // The conductor points to the first node
if ( conductor != 0 ) {
while ( conductor->next != 0)
conductor = conductor->next;
}
conductor->next = new node; // Creates a node at the end of the list
conductor = conductor->next; // Points to that node
conductor->next = 0; // Prevents it from going any further
conductor->x = 42;
}

例如,查看 while ( conductor->next != 0) 行;据我了解,内存中的那个位置可能包含以前使用的垃圾值。当它不再被程序使用时,它会再次可用。那么如何使用整数零作为比较值来检查是否已到达链表的末尾呢?你能保证那个垃圾值是零吗?为什么不是...只是一个随机的垃圾值?

那么,我的理解是完全错误的,还是在之前的程序释放该内存块的过程中,内存重新归零了?过去我一直使用 NULL,认为它是一个神奇的关键字,知道它是在看零值还是垃圾值。但是,阅读上面对其他人问题的回答后,我发现事实并非如此。对于这样一个微不足道的问题,我深表歉意,但每次我在我的应用程序中与 NULL 或零进行比较以检查是否存在某些东西时,我都感到困扰,因为它只是有效,但我不知道为什么。感谢您提供的任何光亮。

最佳答案

首先,Stroustrop 不仅仅是“用户”;他是C++语言的原作者和发明者。这句话来自他的一个 Frequently Asked Questions .

在几乎所有 C 和 C++ 实现中,NULL 只是 0 的#define(文本替换)。所以区别纯粹是美学上的。

没有魔法。也许您不理解“下一个”指针。它是下一个项目的地址,而不是项目本身。由于没有有效的 0 指针,它是一个方便的哨兵或标记,表示列表中没有下一项。如果删除了一个节点,则不会自动将指向它的指针(即位于前一个节点中的下一个指针)设置回 NULL/0。

关于c++ - 了解 C++ 中的零和 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com