多维数组指针在 C 中的工作原理 [英] How Pointer of Multi-Dimension Arrays Work in C
问题描述
我正在试验 C 中指向多维数组的指针的概念.假设我想通过一个函数处理一个多维数组.代码有点像这样:
I'm experimenting with the concept of pointer to multi-dimension array in C. Suppose I want to process a multi-dimensional array via a function. The code kinda looks like this:
#include <stdio.h>
void proc_arr(int ***array)
{
// some code
}
int main(int argc, char **argv)
{
int array[10][10];
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
array[i][j] = i * j;
}
}
proc_arr(&array);
return 0;
}
问题是,当我想访问 proc_arr
中的 array
时,我不能.根据我的理解,我们应该这样访问它:
The problem is, when I want to access array
inside proc_arr
, i can't. From my understanding, we should access it this way:
void proc_arr(int ***array)
{
(*array)[0][1] = 10;
}
所以我取消引用 array
来告诉编译器我想要去那个地址并获取值.但不知何故,它崩溃了.我已经尝试了几种 *
和括号的组合,但仍然无法使其工作.我很确定这是因为我不理解指针和指针的指针.
So I derefer the array
to tell the compiler that I want to go to that address and get the value. But somehow, it crashes. I've tried several combinations of *
and parentheses and still can't make it work. I'm pretty sure it's because of me not understanding pointers and pointers of pointers.
哦,我注意到如果我们使用 char **
(字符串数组)也是不同的,比如 argv 和 envp.但是对于 envp,我可以通过 (*envp)
以某种方式访问它.为什么?
Oh, and I've noticed that it's different if we work with a char **
(array of string) too, like for argv and envp. But for envp, I somehow can access it with (*envp)
. Why?
这是 procces envp(并有效)的函数:
Here's the function that procces envp (and worked):
int envplen(char ***envp)
{
int count = 0;
while((*envp)[count] != NULL)
{
count++;
}
return count;
}
另外,我能否以某种方式访问 envplen
函数中的 envp
仅使用 envp
,但仍然通过引用传递它?
Also, can I somehow access envp
in the envplen
function with only envp
, but still pass it by reference?
之前谢谢.
推荐答案
问题是因为 int array[10][10]
分配在堆栈上并没有按照你想象的方式布置内存做.这是因为数组不是指针.内存仍然以线性阵列布局,而不是二维"阵列,即使下标可能表示如此.换句话说,int array[10][10]
的内存如下所示:
The problem is because int array[10][10]
allocated on the stack does not lay out memory the way you think it does. This is because arrays are not pointers. The memory is still laid out in a linear array, not a "two dimensional" array, even though that's what the subscripts might indicate. In other words, the memory for int array[10][10]
looks like the following:
starting address: ending address:
| Block_1 of 10 int | Block_2 of 10 int | ... | Block_10 of 10 int |
因此,当您将数组隐式转换为 int***
,然后尝试像 (*array)[1][10] 一样访问该数组时,这实际上意味着什么像*(*((*array) + 1) + 10)
,这种操作的内存布局希望看到内存设置如下:
So when you implicitly convert the array to an int***
, and then try to access the array like (*array)[1][10], what this actually translates to is something like *(*((*array) + 1) + 10)
, and the memory layout for such an operation wants to see memory setup like the following:
int*** array
|
|
| Pointer |
|
|
| Pointer_0 | Pointer_1 | ... | Pointer 10 |
| | |
| | | Block of 10 int |
| |
| | Block of 10 int |
|
|Block of 10 int|
这篇关于多维数组指针在 C 中的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!