我为什么要传递一个二维数组到C函数时提供的尺寸? [英] Why must I provide a dimension when passing a two-dimensional array to a C function?
问题描述
我不知道如果记录标记是相关的,但随时添加。
我想presume的原因是历史的,这就是为什么我认为这一点。
为什么我不能声明函数的签名,如下面的?
无效美孚(INT doubly_indexed_array [] []){
...
}
这使得
$ GCC mem.c
mem.c:4:错误:数组类型具有不完整的元素类型
为什么你必须声明的尺寸为下列之一?
无效美孚(INT doubly_indexed_array [] [10]){
...
}
您需要声明第二个,而不是唯一的一个。它具有与存储器布局做,一个2-D阵列连续存储在存储器中,这意味着所有的第二维阵列是contigous
因此,对于 INT [2] [2]
内存布局看起来像(假设初始化为0):
[0,0] [0,0]
编译器有多少就比如第一个维度索引时递增指针就知道了。所以,如果一个int数组被命名为
A [I] [J]
真的是 + I *的sizeof(int)的* second_dimension + J *的sizeof(一个地址)( INT)
所有这一切都需要在编译时已知的,因此编译器可以生成code。
I'm not sure if the history tag is relevant, but feel free to add it. I would presume the reason is historical, which is why I suggest this.
Why is it that I cannot declare a function signature such as the following?
void foo(int doubly_indexed_array[][]) {
...
}
which gives
$ gcc mem.c
mem.c:4: error: array type has incomplete element type
Why must you declare one of the dimensions as in the following?
void foo(int doubly_indexed_array[][10]) {
...
}
You need to declare the second one and not only one. It has to do with memory layout, a 2-d array is stored contiguously in memory which means all the second dimension arrays are contigous.
So for int[2][2]
the memory layout looks like(assuming initialization to 0):
[[0, 0][0, 0]]
Compiler has to know by how much to increment the pointer when indexing on the first dimension for example. So if an int array is named a,
a[i][j]
is really (address of a) + i*sizeof(int)*second_dimension + j*sizeof(int)
All of this need to be known at compile time so the compiler can generate code.
这篇关于我为什么要传递一个二维数组到C函数时提供的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!