C 中二维数组的内存映射 [英] Memory map for a 2D array in C
问题描述
您认为本次讨论关于二维数组是否正确?尤其是这张照片?你能解释一下这个理论吗?>
假设我们像这样在 C 中声明一个二维数组:
int arr[3][3]={10, 20, 30, 40, 50, 60, 70, 80, 90};
现在,根据这个讨论,内存将被安排如下:
现在,我编写了以下代码来测试这个理论:
#include 主要的(){int arr[3][3]={10, 20, 30, 40, 50, 60, 70, 80, 90};printf(" arr==%d
", arr);printf(" &arr[0]==%d
", &arr[0]);printf(" arr[0]==%d
", arr[0]);printf("&arr[0][0]=%d
", &arr[0][0]);printf(" arr[0][0]=%d
", arr[0][0]);}/*输出:========arr ==1245028&arr[0] ==1245028arr[0] ==1245028&arr[0][0]==1245028arr[0][0]==10按任意键继续...*/
为什么前 4 个输出相同?
你的代码只是使用了一个普通的多维数组,但图像描述了一个指针数组,就像你通常在 malloc 时创建的那种.
多维数组基本上只是一个普通的、扁平化的数组(在内存中),带有一些额外的语法糖用于访问.因此,虽然可以从 arr[i] 获取指针,但没有额外的变量"来存储它,就像您的图像中发生的那样.
要校正图像,删除带有arr[0], arr[1]...
的部分并将arr
的值更改为1245039
(与 &arr[0][0] 相同).
Do you think what this discussion about memory-map of 2D array is correct? Especially this photo? Can you explain the theory?
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:
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
", arr);
printf(" &arr[0]==%d
", &arr[0]);
printf(" arr[0]==%d
", arr[0]);
printf("&arr[0][0]=%d
", &arr[0][0]);
printf(" arr[0][0]=%d
", 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...
*/
Why the first 4 outputs are same?
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.
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.
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屋!