【问题标题】:How is this 2D array accessing allocated indexes? [duplicate]这个二维数组如何访问分配的索引? [复制]
【发布时间】:2020-08-29 00:39:06
【问题描述】:

数组如何访问大于其宽度的索引处的值。 我想当你超过大小限制时,它会抛出一个段错误。

#include <iostream>

int main(){

    const int len = 3;
    const int wid = 3;

    int arr[len][wid];

    int count = 1;
    // assigns array to numbers 1 - 9
    for(int i =0;i < len;i++){
        for(int j =0;j< wid;j++){
            arr[i][j] = count++;
        }
    }
    
    int index = 0;
    // prints out the array
    while(index < 9){
        std::cout << arr[0][index++] << " "; // how is it accessing space that wasn't allocated? index++
    }
    std::cout << std::endl;

}

【问题讨论】:

  • 欢迎来到 SO!当您超过大小限制时,行为是不确定的。您的计算机可能会爆炸,或者您可能不小心得到了正确的输出。谁知道呢。
  • int arr[len][wid]; 是非标准的,只能通过编译器扩展获得。另外,回忆一下 C/C++ 中的二维数组(不包括 STL 容器)是一维数组的数组。所以你有len 数组wid 整数。您最后一个有效的列索引是wid-1

标签: c++ arrays segmentation-fault


【解决方案1】:

std::cout

即使项目的总数相同 (9),您也不能只以这种方式从 2D 数组更改为 1D 数组。

看起来您的目的只是打印输入数组,您可能只想像输入时那样循环遍历二维数组索引:

所以不要这样:

// prints out the array
while(index < 9){
    std::cout << arr[0][index++] << " "; // out of bound access - undefined behaviour (crash or worse)
}

这样做:

for (int i = 0; i < len; i++)
{
    for (int j = 0; j < wid; j++)
    {
        cout << arr[i][j] << ' ';
    }
}

【讨论】:

  • @thienpham 而不是崩溃,使用正确的术语是Undefined Behaviour。 UB被憎恨和害怕,因为没有规则。也许你会得到你所期望的。也许你没有得到你所期望的。也许你得到了足够接近的东西,直到your boss is onstage at Comdex 才知道它是错的。您对 UB 的唯一真正防御就是不这样做。幸运的是 there are tools 有时可以帮助你发现你错过了什么。
  • @user4581301 好建议
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多