空指针和指针算术

时间:2020-07-29 12:33:58

标签: c++ arrays pointers pointer-arithmetic

是否有办法在超过40之后停止下面的while循环迭代?我试图复制未找到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;
}

4 个答案:

答案 0 :(得分: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

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

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

这里是booklist

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

有两种方法可以停止循环:使条件变为假,或跳出循环(中断,跳转,返回,抛出等)。您的循环也不执行任何操作。

您的条件为arr,仅当指针指向null时才为false。您永远不会为arr分配null,因此永远不会为null。


我正在尝试复制链表概念

链接列表概念通常不适用于非链接列表。数组不是链接列表。

答案 3 :(得分:0)

int [4]是C数组。而是使用C ++ std :: array及其迭代器:

$dbh = new PDO
  (
    "pgsql:dbname=mydbname;host=myhost;port=5432;options='--client_encoding=UTF8'",
    "username",
    "password"
   );

或者:

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