[英]how to cast void* to int[][3]
I need to pass a variable of type int[][3]
to a callback function which only accepts void*
as parameter. 我需要将
int[][3]
类型的变量传递给一个回调函数,该函数只接受void*
作为参数。 How can I do that? 我怎样才能做到这一点?
The below code does not compile: 以下代码无法编译:
void myfunc(void *param) {
int i[][3];
i=*param;
printf("%d\n",i[1][2]);
}
int main(int argc, char *argv[])
{
int i[][3]={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
myfunc(i);
}
Use: 采用:
int (*i)[3] = param;
Then use it as before. 然后像以前一样使用它。 That's a pointer to an array of integers.
这是一个指向整数数组的指针。
Detailed answer: 详细解答:
i
in main()
is int[3][3]
, an array of arrays. main()
的i
类型是int[3][3]
,一个数组数组。 int[3][3]
is of type int[3]
. int[3][3]
的类型为int[3]
。 int(*)[3]
, so that is what i
ends up as when you type myfunc(i)
. int(*)[3]
类型的数组指针,所以这就是当你输入myfunc(i)
时i
最终的结果。 int(*)[3]
is the correct type to use inside the function. int(*)[3]
是在函数内部使用的正确类型。 int (*i)[3];
int (*i)[3];
inside the function, then acessing i[x]
will give you array number x
in the array of arrays. i[x]
将给出数组数组中的数组x
。 i[x][y]
will give you array number x
, item number y
. i[x][y]
会给你数组编号x
,项目编号y
。 So the syntax ends up the very same as when accessing a 2D array directly. Similarly, you could have written the function as void myfunc(int param[3][3])
. 同样,您可以将函数写为
void myfunc(int param[3][3])
。 Param would implicitly decay into a pointer int(*)[3]
"between the lines", allowing you to use param[x][y]
inside the function. Param会隐式地衰减到指针
int(*)[3]
“在行之间”,允许你在函数内部使用param[x][y]
。 It only looks like the array is passed by value, but it isn't - doing that isn't possible in C. 它看起来只是数组按值传递,但它不是 - 在C中这样做是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.