存储器映射在C二维数组 [英] Memory map for a 2D array in C
问题描述
你觉得什么这个讨论了解二维数组的内存映射是正确的? 尤其是照片你能解释一下原理是什么?
Do you think what this discussion about memory-map of 2D array is correct? Especially this photo? Can you explain the theory?
假设我们用C声明一个二维数组是这样的:
Suppose we declare a 2D array in C like this:
int arr[3][3]={10, 20, 30, 40, 50, 60, 70, 80, 90};
现在,根据本讨论中,存储器会安排如下所示:
Now, according to this discussion, the memory would be arranged like the following:
现在,我写了下面的code测试这种理论:
Now, I have written the following code to test this theory:
#include <stdio.h>
main()
{
int arr[3][3]={10, 20, 30, 40, 50, 60, 70, 80, 90};
printf(" arr==%d\n", arr);
printf(" &arr[0]==%d\n", &arr[0]);
printf(" arr[0]==%d\n", arr[0]);
printf("&arr[0][0]=%d\n", &arr[0][0]);
printf(" arr[0][0]=%d\n", arr[0][0]);
}
/*
Output:
========
arr ==1245028
&arr[0] ==1245028
arr[0] ==1245028
&arr[0][0]==1245028
arr[0][0]==10
Press any key to continue...
*/
为什么第4个输出相同?
Why the first 4 outputs are same?
推荐答案
您code只使用一个简单的多维数组,但图像描述指针数组,喜欢那种你通常当的malloc-ING的事情做。
Your code just uses a plain multidimensional array, but the image describes an array of pointers, like the kind you usually make when malloc-ing things.
一个多维数组基本上是一个正常的,扁平的,阵列(在内存中),以访问一些额外的语法糖。因此,尽管有可能从ARR [I]得到一个指针,没有一个额外的变量只是存储这一点,因为在你的形象发生了。
A multidimensional array is basically just a normal, flattened, array (in memory) with some extra syntatic sugar for accessing. So while it is possible to get a pointer from arr[i], there isn't an extra "variable" just to store this, as happens in your image.
要校正图像,用改编[0],ARR [1] ...
和改变的值改编去除部分
到 1245039
(同为&放大器;常用3 [0] [0])。
To correct the image, remove the parts with the arr[0], arr[1]...
and change the value of arr
to 1245039
(the same as &arr[0][0]).
这篇关于存储器映射在C二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!