简体   繁体   English

如何将void *转换为int [] [3]

[英]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: 详细解答:

  • The type of i in main() is int[3][3] , an array of arrays. main()i类型是int[3][3] ,一个数组数组。
  • When you use that as part of an expression, it "decays" into a pointer to the first element. 当您将其用作表达式的一部分时,它会“衰减”为指向第一个元素的指针。
  • The first element of the array int[3][3] is of type int[3] . 该阵列的第一个元素int[3][3]的类型为int[3]
  • A pointer to that first element is an array pointer of type int(*)[3] , so that is what i ends up as when you type myfunc(i) . 指向第一个元素的指针是int(*)[3]类型的数组指针,所以这就是当你输入myfunc(i)i最终的结果。
  • Therefore, int(*)[3] is the correct type to use inside the function. 因此, int(*)[3]是在函数内部使用的正确类型。
  • If you have 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. 因此,语法最终与直接访问2D数组时的语法相同。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM