我正在尝试制作二维数组,将其传递给函数,然后更新 main 中修改后的数组
编译器显示:
Warning: passing argument 1 of 'fun' from incompatible
pointer type; note: expected 'int ()[5]' but argument
is of type 'int (*)[5][5]'
代码:
#include<stdio.h>
void fun(int * b[][5])
{
int x=11,y=90;
printf("here");
*b[1][3] = x;
*b[3][1] = y;
*b[2][2] = x + ++y;
}
int main()
{
int a[5][5];
a[1][3] = 12;
a[3][1] = 145;
fun(&a);
printf("%d %d %d",a[1][3],a[3][1],a[2][2]);
}
The compiler shows:
Warning: passing argument 1 of 'fun' from incompatible
pointer type; note: expected 'int ()[5]' but argument
is of type 'int (*)[5][5]'
Code:
#include<stdio.h>
void fun(int * b[][5])
{
int x=11,y=90;
printf("here");
*b[1][3] = x;
*b[3][1] = y;
*b[2][2] = x + ++y;
}
int main()
{
int a[5][5];
a[1][3] = 12;
a[3][1] = 145;
fun(&a);
printf("%d %d %d",a[1][3],a[3][1],a[2][2]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要在函数参数中使用星号,也不需要在函数中取消引用数组 b。数组通过引用传递(因此也去掉 foo(&a) 中的 & 符号),因为 C 将它们视为指向序列中第一个元素的指针。
多维数组被视为指向较小子数组开头的指针数组,即数组的数组。与上面的解释相同。
您的代码最终应该如下所示:
You do not need the asterisk in your function parameters, and you don't need to dereference the array b in your function. Arrays are passed by reference (so get rid of the ampersand in foo(&a) as well), because C treats them as pointers to the first element in the sequence.
Multidimensional arrays are treated as arrays of pointers to the start of smaller sub-arrays, i.e. arrays-of-arrays. Same explanation as above applies.
Your code should look like this in the end:
当数组传递给函数时,真正传递的是指向数组第一个元素的指针。
因此,使用
fun(a)
调用fun()
函数实际上会将指针传递给a
第一个元素,在本例中是一个 int 数组大小为 5。函数fun()
将接收一个指向大小为 5 的 int 数组的指针,即int (*b)[5]
。请注意,int *b[5]
并不相同,它是一个包含 int 指针的大小为 5 的数组。你的 fun 函数可以有:
或者
第一种方法表示该函数将接收一个 2d 整数数组,但因为我们知道实际将发送到该函数的是一个指向数组
a
的第一个元素,编译器将悄悄地编译该函数,就好像该参数是一个指针一样,因为它将接收一个指针。第二种方法显式显示它将接收的类型,即指向大小为 5 的数组的指针。
When arrays are passed to a function, what really gets passed is a pointer to the arrays first element.
So calling the
fun()
function withfun(a)
will actually pass the pointer to thea
first element, in this case an int array of size 5. The functionfun()
will receive a pointer to an int array of size 5, that is to sayint (*b)[5]
. Note thatint *b[5]
is not the same and is an array of size 5 containing int pointers.Your
fun
function can either have:or
The first way to do it says that the function will receive a 2d array of ints, but since we know that what actually will be sent to the function is a pointer to the first element of the array
a
, the compiler will quietly compile the function as if the parameter were a pointer, since it's a pointer that it will receive.The second way to do it explicitly shows what type it will receive, a pointer to an array of size 5.