问题描述
在 C 中,我知道我可以使用以下代码在堆上动态分配一个二维数组:
In C, I know I can dynamically allocate a two-dimensional array on the heap using the following code:
int** someNumbers = malloc(arrayRows*sizeof(int*));
for (i = 0; i < arrayRows; i++) {
someNumbers[i] = malloc(arrayColumns*sizeof(int));
}
显然,这实际上创建了一个一维指针数组,指向一堆单独的一维整数数组,当我要求时,系统"可以弄清楚我的意思:
Clearly, this actually creates a one-dimensional array of pointers to a bunch of separate one-dimensional arrays of integers, and "The System" can figure out what I mean when I ask for:
someNumbers[4][2];
但是当我静态声明一个二维数组时,如下行...:
But when I statically declare a 2D array, as in the following line...:
int someNumbers[ARRAY_ROWS][ARRAY_COLUMNS];
...是否在堆栈上创建了类似的结构,还是完全是另一种形式?(即它是一维指针数组吗?如果不是,它是什么,以及如何找出对它的引用?)
...does a similar structure get created on the stack, or is it of another form completely? (i.e. is it a 1D array of pointers? If not, what is it, and how do references to it get figured out?)
此外,当我说系统"时,究竟是什么负责解决这个问题?内核?还是C编译器在编译的时候整理出来的?
Also, when I said, "The System," what is actually responsible for figuring that out? The kernel? Or does the C compiler sort it out while compiling?
推荐答案
静态二维数组看起来像数组的数组 - 它只是在内存中连续排列.数组与指针不同,但因为你经常可以互换使用它们,所以有时会让人感到困惑.不过,编译器会正确跟踪,这使得一切都很好.你必须小心你提到的静态二维数组,因为如果你试图将一个数组传递给一个带有 int **
参数的函数,那么糟糕的事情就会发生.这是一个简单的例子:
A static two-dimensional array looks like an array of arrays - it's just laid out contiguously in memory. Arrays are not the same thing as pointers, but because you can often use them pretty much interchangeably it can get confusing sometimes. The compiler keeps track properly, though, which makes everything line up nicely. You do have to be careful with static 2D arrays like you mention, since if you try to pass one to a function taking an int **
parameter, bad things are going to happen. Here's a quick example:
int array1[3][2] = {{0, 1}, {2, 3}, {4, 5}};
在内存中看起来像这样:
In memory looks like this:
0 1 2 3 4 5
完全等同于:
int array2[6] = { 0, 1, 2, 3, 4, 5 };
但是如果你尝试将 array1
传递给这个函数:
But if you try to pass array1
to this function:
void function1(int **a);
您将收到警告(并且应用程序将无法正确访问数组):
you'll get a warning (and the app will fail to access the array correctly):
warning: passing argument 1 of ‘function1’ from incompatible pointer type
因为二维数组与int **
不同.可以这么说,数组自动衰减为指针只会进入一级深度".您需要将该函数声明为:
Because a 2D array is not the same as int **
. The automatic decaying of an array into a pointer only goes "one level deep" so to speak. You need to declare the function as:
void function2(int a[][2]);
或
void function2(int a[3][2]);
为了让一切都快乐.
同样的概念扩展到 n 维数组.但是,在您的应用程序中利用这种有趣的业务通常只会使其更难理解.所以在外面要小心.
This same concept extends to n-dimensional arrays. Taking advantage of this kind of funny business in your application generally only makes it harder to understand, though. So be careful out there.
这篇关于多维数组在内存中是如何格式化的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!