如何使用1维访问C中的2D数组 [英] How does accessing a 2D array in C with 1 dimension work
问题描述
我试图理解一些C代码,但无法解决以下问题:
I'm trying to understand some C code and I can't wrap my head around the following issues:
-
为什么通过以1维访问数组来打印数组会颠倒存储值的打印顺序?
Why does printing an array by accessing it with 1 dimension reverse the order the values in which the stored values print?
如果将数组声明为 [3] [4]
数组,是否可以在 array [3] [x]
处引用值?
If the array was declared as a [3][4]
array, is it possible to reference a value at array[3][x]
?
作者初始化了一个二维数组- word [3] [4]
,根据我的理解,该数组在内存中创建了一个3行/4列的数组-
The author initializes a 2d array - word[3][4]
, which based on my understanding creates a 3 row/4 column array in memory-
Col 0 Col 1 Col 2 Col 3
Row 0 [0][0] [0][1] [0][2] [0][3]
Row 1 [1][0] [1][1] [1][2] [1][3]
Row 2 [2][0] [2][1] [2][2] [2][3]
稍后,将值写入数组,并根据变量 z
从 0-3
开始对行进行硬编码并更改列,
Later, values are written to the array hardcoding the row and changing the column based on a loop control valriable, z
, going from 0-3
:
word[0][z]
word[1][z]
word[2][z]
word[3][z]
最后,通过引用一个维度来显示数组:
At the end, the array is displayed by referencing one dimension:
printf("%x", *((unsigned int *)word[i]));
这似乎是要反向打印存储在内存中的值:
This appears to print the values stored in memory in reverse:
75757575
42424242
48484849
即使它们被保存在内存中,如下所示:
even though they are held in memory as shown below:
0xbfa33050: 75757575
0xbfa33054: 42424242
0xbfa33058: 49484848
有想法吗?
推荐答案
为什么通过反向访问一维数组来打印数组存储值的打印顺序如何?
Why does printing an array by accessing it with 1 dimension reverse the order the values in which the stored values print?
因为它们连续存储在内存中.
Because they are stored in contiguous in memory.
如果将该数组声明为[2] [3]数组,则可以当仅声明3个时引用第四行吗?
If the array was declared as a [2][3] array, is it possible to reference a 4th row when only 3 were declared?
如果这样做,则您尝试访问绑定元素之外的.
If you do so, you are trying to access out of bound elements.
这似乎是要反向打印存储在内存中的值-
This appears to print the values stored in memory in reverse-
因为这就是将其存储在堆栈中的原因!
Because that's how it is stored in stack!
有关更多详细信息,您可以参考此图片
For more details you can refer this image
这篇关于如何使用1维访问C中的2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!