【发布时间】: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