C 2D Array同时更改2个元素

标签 c arrays multidimensional-array

<分区>

这是我的二维数组 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 |
+---+------------+------------+------------+------------+------------+------------+

关于C 2D Array同时更改2个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772607/

相关文章:

c - C中结构体数组的静态分配

java - 访问arraylist哪种方式更好

c++ - 指向二维数组的指针的 C/C++ 数组

c - 链表未释放,丢失内存泄漏

c - 宏和后增量

c - 为什么这段代码会超出范围?

C:统计一个int型数组的实际大小

php - 在PHP中删除多维数组中特定键的重复值但删除最后一个?

java - Java中的多维数组长度

c - C 有 stackalloc 函数吗?