casting void** to 2D array of int - C
我正在尝试将void **指针转换为C中的int ** 2D数组
这是我尝试使用的代码(删除了所有无关的比特):
1 2 3 4 5 6 7 8 9 10 11 12 13 | \*assume that i have a data structure called graph with some *element"void** graph" in it and some element"int order" */ void initialise_graph_data(graph_t *graph) { void **graph_data = NULL; int (*matrix)[graph->order]; size_t size = (graph->order * graph->order) * sizeof(int); graph_data = safe_malloc(size); /*safe malloc works fine*/ matrix = (int(*)[graph->order])graph_data; graph->graph = graph_data; } |
当我编译它时,它工作正常,但警告我设置了变量" matrix"但未使用。 我真的不想使用临时矩阵变量,因为该函数只是应该初始化数组,而不要在其中放入任何内容; 但是如果我尝试将graph_data直接转换为int **时,如下所示:
1 | graph->graph = (int(*)[graph->order])graph_data; |
它给了我不兼容的指针类型警告的分配。
我只是不能正确投射吗? 有没有人对我如何在没有临时" matrix"变量的情况下使它工作有任何建议? 还是如果没有,我该如何处理该变量,以便它不会向我发出已设置但未使用的警告?
谢谢
编译器是正确的,数组的数组(或指向数组的指针)与指向指针的指针不同。 只要考虑一下它们在内存中的布局方式:
大小为MxN的矩阵,形式为数组数组:
1 2 3 | +--------------+--------------+-----+----------------+--------------+-----+------------------+ | matrix[0][0] | matrix[0][1] | ... | matrix[0][N-1] | matrix[1][0] | ... | matrix[M-1][N-1] | +--------------+--------------+-----+----------------+--------------+-----+------------------+ |
A和相同的"矩阵"以指针的形式指向指针:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | +-----------+-----------+-----------+-----+ | matrix[0] | matrix[1] | matrix[2] | ... | +-----------+-----------+-----------+-----+ | | | | | V | | +--------------+--------------+-----+ | | | matrix[2][0] | matrix[2][1] | ... | | | +--------------+--------------+-----+ | | | V | +--------------+--------------+-----+ | | matrix[1][0] | matrix[1][1] | ... | | +--------------+--------------+-----+ | V +--------------+--------------+-----+ | matrix[0][0] | matrix[0][1] | ... | +--------------+--------------+-----+ |
分配正确的大小无关紧要,这两个变量根本不兼容,这就是编译器告诉您的。