【问题标题】:Null pointer and pointer arithmetic空指针和指针运算
【发布时间】:2020-07-29 12:33:58
【问题描述】:

有没有办法阻止下面的 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;
}

【问题讨论】:

  • 指针在到达数组末尾时不会变为 NULL。 C++ 不能以这种方式工作。
  • 简答:否。
  • (arr+4) 不为空。你可以试试std::cout&lt;&lt; (arr++) 看看你得到了什么。
  • 链表概念适用于链表。动态数组在现代 C++ 中是一种难闻的气味。你想要一个std::vector
  • int count = 4; while(count--) { ... }

标签: c++ arrays pointers pointer-arithmetic


【解决方案1】:

因为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

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

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

这是booklist

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      超过40后是否要停止下面的while循环迭代

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

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


      我正在尝试复制链表的概念

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

      【讨论】:

        【解决方案4】:

        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;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-01-13
          • 1970-01-01
          • 1970-01-01
          • 2016-03-27
          • 2011-04-04
          • 2015-10-21
          • 1970-01-01
          相关资源
          最近更新 更多