空指针和指针运算

Null pointer and pointer arithmetic

有没有办法让下面的while循环在超过40之后不再继续迭代?我正在尝试复制链表迭代的概念,而 NULL 指针未找到。

int main() {
    int* arr = new int[4]{ 10,20,30,40 };
    //for(int i=0; i<4; ++i) -- works fine
    while (arr) {
        cout << *(arr++) << endl;
    }
        
    delete[] arr; // Free allocated memory
    return 0;
}

Is there are to stop the while loop below from iterating after surpassing 40

有两种方法可以停止循环:使条件变为假,或者跳出循环(break、goto、return、throw等)。你的循环也不做。

你的条件是 arr 只有当指针指向 null 时才为假。您永远不会将 null 分配给 arr,因此它永远不会为 null。


I am trying to replicate the linked list concept

链表概念通常不适用于非链表的事物。数组不是链表。

因为arr被放置在一个连续的内存中,你永远不会在arr.

之后得到内存地址的NULL值

您可以尝试 following code 在线编译器。

#include <iostream>

int main()
{
    int* arr = new int[4]{ 10,20,30,40 };
    for(int i=0; i<4; ++i){
        std::cout << *(arr++) << std::endl;
        std::cout << arr << std::endl;
    }
    std::cout << "NULL is " << (int*)NULL; // NULL mostly stands for 0.
    return 0;
}

输出可能是这样的:

10    
0x182de74    
20    
0x182de78    
30    
0x182de7c    
40    
0x182de80    
NULL is 0

为什么链表有效?因为链表将数据存储在非连续的内存中,并且 next() 会给你 NULL 作为列表结尾的标志。

您可能还需要一本 C++ 基础书籍。

这是 booklist

使用保留值(例如零)并将其附加到数组的末尾,就像使用旧的 C 字符串一样。这称为哨兵元素。

int* arr = new int[4]{ 10,20,30,40,0 };
while (*arr) {
      ...

int[4] 是一个 C 数组。相反,使用 C++ std::array 及其迭代器:

#include <array>
#include <iostream>

int main() // Print all items
{
    std::array<int, 4> arr{ 10, 20, 30, 40 };

    for (auto i : arr)
        std::cout << i << std::endl;
}

或者:

#include <array>
#include <iostream>

int main() // Print until the 1st 0 item
{
    std::array<int, 6> arr{ 10, 20, 30, 40, 0, 0 };

    for (auto i : arr) {
        if (i == 0)
            break;
        std::cout << i << std::endl;
    }
}