简体   繁体   English

cpp 2D阵列会自行改变吗?

[英]cpp 2D array changes on its own?

In the following piece of code i create a 2D array, tab. 在下面的代码中,我创建了一个2D数组,tab。 Let len_a=5,len_b=4 After the first for loop, tab[0][5] should be equal to 5, and it is. len_a=5,len_b=4在第一个for循环之后, tab[0][5]应该等于5。 But, when i print the row, it changes value to 1. What's happening? 但是,当我打印该行时,它将值更改为1。发生了什么事?

int len_a=a.length(),len_b=b.length();

    int tab[len_a+1][len_b+1];
    tab[0][0]=0;


    for(int i=1;i<=len_a;i++)//Init first row
        tab[0][i]=i;

    cout<<tab[0][5]<<endl;


    for(int j=1;j<=len_b;j++)//Init first column
        tab[j][0]=j;

    for(int i=0;i<=len_a;i++)//Print row
        cout<<tab[0][i]<<" | "<<i<<endl;

    cout<<endl;
    for(int i=0;i<=len_b;i++)
        cout<<tab[i][0]<<" | "<<i<<endl;    

Outputs: 输出:

5 (first cout<< tab[0][5]) 5(第一个cout <<制表符[0] [5])

0 | 0 | 0 0

1 | 1 | 1 1个

2 | 2 | 2 2

3 | 3 | 3 3

4 | 4 | 4 4

1 | 1 | 5 (second cout<< tab[0][5] ???) 5(第二个cout << tab [0] [5] ???)

0 | 0 | 0 0

1 | 1 | 1 1个

2 | 2 | 2 2

3 | 3 | 3 3

4 | 4 | 4 4

C++ has 0 indexed arrays, which means that first element is 0 and last is N-1. C ++具有0个索引数组,这意味着第一个元素为0,最后一个元素为N-1。

Example: 例:

tab[2][3]; //creating array

tab[0][0]; //first element of array
tab[0][1];
tab[0][2]; //last element in the first row
tab[1][0];
tab[1][1];
tab[1][2]; //last element in the second row and last element in array

Any other element not mentioned above, like tab[2][...] or tab[...][3] is outside declared bounds array. 上面未提及的任何其他元素,例如tab[2][...]tab[...][3]都在声明的边界数组之外。

Since in example there was tab[6][5] created, cout << tab[0][5]; 由于在示例中创建了tab[6][5] ,因此cout << tab[0][5]; is accessing something that is out of tab bounds. 正在访问超出tab范围的内容。 As @Bob__ mentioned arrays allocate continuous memory, so by accessing tab[0][5] in fact tab[1][0] is accessed. 正如@Bob__提到的那样,数组分配了连续的内存,因此实​​际上通过访问tab[0][5] tab[1][0]可以访问tab[1][0] Second access to tab[1][0] element is after //Init first column occurred which overwrite value in tab[1][0] element. //Init first column之后对tab[1][0]元素的第二次访问将覆盖tab[1][0]元素中的值。

BTW: In the example there is first bracket swap with second. 顺便说一句:在该示例中,有一个第一方括号与第二个方括号互换。 There should be: 应该有:

int tab[len_a][len_b];

for(int i=0; i<=len_a; i++)//Init first row
    tab[i][0]=i; //not tab[0][i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM