为什么 C++ 中数组中的零被视为 NULL(使用代码块)?

Why zero in array in C++ is considered as NULL(using CODEBLOCKS)?

我在数组中输入了零作为整数,当使用函数打印数组 (show()) 时,它退出函数时将零视为 NULL。

数组 = {1,2,3,0,4,5}

预期输出 = 1 2 3 0 4 5

输出=1 2 3

为什么会这样? CodeBlocks 设置有问题吗?

谢谢

 int show(int arr[])                               //p r i n t   a r r a y
{
    int i;
    for(i = 0; arr[i]!='[=10=]'; ++i)
    {
        cout<<arr[i]<<"\t";
    }
    if(arr[0]=='[=10=]')
        cout<<"Emptry Array";
    return 0;
}

'[=10=]' 是一个 char 类型常量,数值为 0。

将其与 0 进行比较,后者是一个 int 类型常量,数值为 0。(有趣的事实:它实际上是一个 octal 常量,因为它以 0!)

开头

有些人也使用 NULL 来表示零,尤其是在使用指针时。在 C++ 中,它需要严格设置为 0,或者类型为 std::nullptr_tprvalue。 (与 C 相比,(void*)0 通常是定义。)

从 C++11 开始,您应该使用 nullptr 来表示空指针值。


许多人随意使用 0、[=19=]、NULL 和 nullptr,而不管它们表示什么。以上为指导。

expected output = 1 2 3 0 4 5

output = 1 2 3

Why is it so?

简而言之:因为您的循环在遇到等于 '[=11=]'0 == '[=12=]' 的元素时停止。

澄清一下,'[=11=]'是一个值为0的字符字面量。字符类型是整数类型。此外,NULL 是一个扩展为空指针常量的宏。 NULL示例程序中根本没有使用宏。

请注意,如果您要传递一个指向不包含 0 的数组的指针,则循环不会在到达数组末尾之前结束,因此会溢出它,以及程序的行为将是未定义的。

What shall I use instead?

如果你想遍历数组的 6 个元素,那么你可以使用这样的循环:

std::size_t count = 6;
for (std::size_t i = 0; i < count; i++)

any general way to reach the last element in an integer array?

最后一个元素的索引是数组中元素的个数减一。

Just to append it.

无法追加到数组。数组的大小在数组的整个生命周期内保持不变。

Is something wrong with the CodeBlocks settings?

我认为没有理由怀疑这一点。

I've entered zero as an integer in an array and when using a function to print array (show()) it exits the function considering the ZERO as NULL. Why is it so?

在这种情况下,它用于指示数组的结尾(因为函数没有其他方法可以知道数组的结尾位置)。 '[=11=]',即 char 将被提升为具有值 0int,用作特殊值,应该 而不是 是正常数据的一部分。因为您应该将 0 视为任何其他无效的 intints 没有 null 状态 - 它们只有整数值。


这是一种非常C-类似的数据传递方式。与下面的非常相似,它支持将 0 作为数组中的值:

int show(int arr[], size_t array_length)
{
    if(array_length == 0) cout<<"Empty Array";
    else for(size_t i = 0; i < array_length; ++i)
    {
        cout<<arr[i]<<"\t";
    }
    return 0; // why does this function return anything? Make it void.
}