[英]casting void** to 2D array of int - C
我正在嘗試將 void** 指針轉換為 C 中的 int** 2D 數組
這是我正在嘗試使用的代碼(刪除了所有無關位):
\*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;
}
當我編譯它時,它工作正常,但給我一個警告,即變量“矩陣”已設置但未使用。 我真的不想使用臨時矩陣變量,因為該函數只是應該初始化數組,而不是在其中放置任何東西; 但是如果我嘗試將 graph_data 直接轉換為 int** 當我將其分配給 graph->graph 時,如下所示:
graph->graph = (int(*)[graph->order])graph_data;
它給了我一個來自不兼容指針類型警告的賦值。
我只是沒有正確投射嗎? 有沒有人對我如何在沒有臨時“矩陣”變量的情況下使其工作有任何建議? 或者如果沒有,我可以用那個變量做什么,這樣它就不會給我設置但未使用的警告?
謝謝
編譯器是對的,數組數組(或指向數組的指針)與指向指針的指針不同。 想想它們在內存中的排列方式:
數組形式的大小為 MxN 的矩陣:
+--------------+--------------+-----+----------------+--------------+-----+------------------+ | matrix[0][0] | matrix[0][1] | ... | matrix[0][N-1] | matrix[1][0] | ... | matrix[M-1][N-1] | +--------------+--------------+-----+----------------+--------------+-----+------------------+
A 和同一個“矩陣”的指針形式:
+-----------+-----------+-----------+-----+ | 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] | ... | +--------------+--------------+-----+
如果您分配正確的大小並不重要,這兩個變量根本不兼容,這就是您的編譯器告訴您的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.