这是我的二维数组 int myarray[79][24];
每当我更改第 0 行的元素时,它会同时更改第 24 行的另一个元素,反之亦然。
例如,myarray[35][0] = 'X';
更改 myarray[35][0]
和 myarray[34][24 ]
同时到 X。当我尝试 myarray[40][24] = 'X';
它改变了 myarray[40][24]
和 myarray[41][0]
同时。
看起来第一行和最后一行是相互镜像的。我怎样才能阻止这种情况发生?
规范:6.5.2.1 Array subscripting
Successive subscript operators designate an element of a multidimensional array object.
If E is an n-dimensional array (n ≥ 2) with dimensions i × j × ... × k, then E (used as
other than an lvalue) is converted to a pointer to an (n − 1)-dimensional array with
dimensions j × ... × k. If the unary * operator is applied to this pointer explicitly, or
implicitly as a result of subscripting, the result is the referenced (n − 1)-dimensional
array, which itself is converted into a pointer if used as other than an lvalue. It follows
from this that arrays are stored in row-major order (last subscript varies fastest).
C 是一种允许程序员做很多事情的语言。例如,没有 IndexOutOfBoundsError
。数组只是指向第一个单元格的指针,然后它保留了数组长度的下一个单元格。
当您声明 int[79][24] 时,它会保留 79*24 个单元格。他们一个接一个。如果数组维度为 79x24,则第一维的索引为 0-78,第二维的索引为 0-23。地址 34,24 处的单元格实际上是 34,23 之后的一个单元格,即内存中的 35,0。
让我们举一个大小为 6x4 的数组的例子:
Your array represented as expected by you with values:
+---+---+---+---+---+---+---+
| | 0 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+
| 1 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+
| 2 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+
| 3 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+
Your array with cell adresses (where start is the adress of cell 0,0):
+---+------------+------------+------------+------------+------------+------------+
| | 0 | 1 | 2 | 3 | 4 | 5 |
+---+------------+------------+------------+------------+------------+------------+
| 0 | start | start + 1 | start + 2 | start + 3 | start + 4 | start + 5 |
+---+------------+------------+------------+------------+------------+------------+
| 1 | start + 6 | start + 7 | start + 8 | start + 9 | start + 10 | start + 11 |
+---+------------+------------+------------+------------+------------+------------+
| 2 | start + 12 | start + 13 | start + 14 | start + 15 | start + 16 | start + 17 |
+---+------------+------------+------------+------------+------------+------------+
| 3 | start + 18 | start + 19 | start + 20 | start + 21 | start + 22 | start + 23 |
+---+------------+------------+------------+------------+------------+------------+