传递给函数的多维数组的指针类型是什么? [英] What is the pointer type of a multidimensional array when passed to a function?
问题描述
我在大学课堂上正在学习C和指针,我认为除了多维数组和指针之间的相似性以外,我对这个概念已经有了很好的了解.
I'm learning about C and pointers in my university class, and I think I've got a pretty good grasp on the concept except for the similarity between multidimensional arrays and pointers.
我认为,由于所有数组(甚至多维数组)都存储在连续的内存中,因此您可以安全地将其转换为int*
(假设给定的数组为int[]
.)但是,我的教授说,数字定义中的星数取决于数组中维数的数量.因此,int[]
将成为int*
,int[][]
将成为int**
,依此类推.
I thought that since all arrays (even multidimensional) ones are stored in continuous memory, you could safely convert it to a int*
(assuming the given array is an int[]
.) However, my professor said that the number of stars in the definition depends on the number of dimensions in the array. So, an int[]
would become an int*
, a int[][]
would become an int**
, etc.
所以我写了一个小程序来测试这个:
So I wrote a small program to test this:
void foo(int** ptr)
{
}
void bar(int* ptr)
{
}
int main()
{
int arr[3][4];
foo(arr);
bar(arr);
}
令我惊讶的是,编译器在两个函数调用上均发出了警告.
To my surprise, the compiler issued warnings on both function calls.
main.c:22:9: warning: incompatible pointer types passing 'int [3][4]' to parameter of type
'int **' [-Wincompatible-pointer-types]
foo(arr);
^~~
main.c:8:16: note: passing argument to parameter 'ptr' here
void foo(int** ptr)
^
main.c:23:9: warning: incompatible pointer types passing 'int [3][4]' to parameter of type
'int *' [-Wincompatible-pointer-types]
bar(arr);
^~~
main.c:13:15: note: passing argument to parameter 'ptr' here
void bar(int* ptr)
^
2 warnings generated.
这是怎么回事?您如何更改函数调用,以便其中一个可以接受数组?
What's going on here? How could you change the function calls so one of them would accept the array?
This is not a duplicate of How to pass a multidimensional array to a function in C and C++ because I'm asking how to change the function calls themselves, not the function signatures.
推荐答案
数组和指针并非完全可以自由转换.为了不发出警告,您需要使用void foo(int (*ptr)[4])
之类的签名.将类似的数组传递给函数时,只能用*替换第一个[].
Arrays and pointers aren't entirely freely convertible. To not get a warning, you'd need a signature like void foo(int (*ptr)[4])
. You can only replace the first [] with a * when passing an array like that to a function.
这篇关于传递给函数的多维数组的指针类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!