我已經超過 25 年沒有撰寫 C 了,顯然我已經忘記了很多,而且編譯器現在比以前嚴格得多。因此,我正在努力創建一個動態分配的指標陣列,該陣列指向 8 個無符號字符的陣列。
我相信我需要一個作為指標的變數。我希望在運行時分配該變數以指向動態分配的指標陣列。然后將每個結果指標分配給指向 8 個無符號字符的陣列。
我認為我的陣列的變數宣告應該是:
int (**arr)[8];
但我無法弄清楚如何分配存盤空間。
第一步,我嘗試了很多關于這個想法的變體:
arr = new (int*[8])[4];
但都被拒絕為型別不兼容或語法錯誤。無奈之下,我也試過:
arr = malloc(4 * sizeof(void *));
這被拒絕了“無法將'void *'轉換為'int(**)[8]'”所以我嘗試了一個演員:
arr = (int**[8])malloc(4 * sizeof(void *));
仍然失敗。
編輯:根據迄今為止的評論,首先,我正在用 C 撰寫 ESP32 設備,現在已經取得了進展(仍然失敗)
arr = new (int(*)[8])[4]; // array bound forbidden after parenthesized type
和
arr = new (int(*)[])[4]; // cannot convert ‘int (**)[]’ to ‘int (**)[8]’
從評論中可以清楚地看出“我需要重新學習很多東西”,甚至“這不是最好的方法”,但現在我只想完成作業。誰能簡單地告訴我a)我的變數宣告是否正確,以及b)我如何分配初始指標陣列?
uj5u.com熱心網友回復:
相信你想了解**雙指標以及如何使用它們。
// explanation of what double pointer is.
int **arr1; //double pointer: is a pointer to point to pointer
// example
int* p = new int(1);
arr1 = &p; // points to pointer int*, note the "&" affront which returns the memory address of p.
arr1 = new int*[10]; // points to int*, "new" returns the memory address of newly allocated memory space.
// harder example, how to point to a double array [][]
int num_rows = 10;
arr1 = new int*[num_rows];
for (int i = 0; i < num_rows; i)
{
int num_cols = i 1; // the column length can be different for each row
arr1[i] = new int[num_cols];
for (int j = 0; j < num_cols; j)
arr1[i][j] = i;
}
請注意,** 不僅指向那些具有固定長度的行,它還可以指向不等長的資料行,如示例所示。注意跟蹤行長度或只使用雙陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463122.html
上一篇:Nginx重寫任何arg名稱
