Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 这个2D数组如何访问分配的索引?_C++_Arrays_Segmentation Fault - Fatal编程技术网

C++ 这个2D数组如何访问分配的索引?

C++ 这个2D数组如何访问分配的索引?,c++,arrays,segmentation-fault,C++,Arrays,Segmentation Fault,数组如何在大于其宽度的索引处访问值。 我想当你超过尺寸限制时,会抛出一个segfault错误 #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++){

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

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

}
#包括
int main(){
常数int len=3;
常数int wid=3;
国际协议[长][宽];
整数计数=1;
//将数组分配给数字1-9
对于(int i=0;istd::不欢迎这么做!当您超过大小限制时,行为是未定义的。您的计算机可能会爆炸,或者您可能意外获得正确的输出。谁知道呢。
int-arr[len][wid];
是非标准的,仅由编译器扩展提供。另外,请回想一下C/C++中的2D数组(不包括STL容器)是1D数组的数组。因此您有
len
数组的
wid
整数。最后一个有效的列索引是
wid-1
。欢迎使用So!当您超过大小限制时,行为未定义。您的计算机可能会爆炸,或者可能意外获得正确的输出。谁知道呢。
int-arr[len][wid];
是非标准的,仅由编译器扩展提供。另外,请调用C/C++中的2D数组(不包括STL容器)是1D数组的数组。所以你有
len
数组的
wid
整数。你最后一个有效的列索引是
wid-1
@thienpham,而不是crash,正确的术语是。UB因为没有规则而被憎恨和害怕。也许你得到了你想要的。也许你没有得到你想要的。也许你没有得到你想要的。也许你得到了你想要的够了,直到你知道它是错的。你对UB唯一真正的防御就是不去做。幸运的是,这有时可以帮助你发现你错过了什么。@user4581301很好advice@thienpham与其说崩溃,还不如说是。UB被憎恨和恐惧,因为没有规则。也许你得到了你想要的。也许你没有得到w这正是你所期望的。也许你离某个地方足够近,直到你知道它错了。你唯一真正的防御UB的方法就是不要这样做。幸运的是,这有时可以帮助你发现你错过了什么。@user4581301好建议
// 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] << ' ';
    }
}