我已經宣告了一個 typedef:
typedef float Matrix[3][3];
我現在正在嘗試為該陣列分配記憶體:
Matrix* matPtr = malloc(sizeof(Matrix));
if (matPtr != NULL)
{
for (int r = 0; r < 3; r )
{
for (int c = 0; c < 3; c )
{
*matPtr[r][c] = 0;
}
}
}
但我得到了錯誤:
嚴重性代碼 描述 專案檔案行抑制狀態警告 C6200 索引“2”超出了非堆疊緩沖區“matPtr”的有效索引范圍“0”到“0”。
我究竟做錯了什么?
uj5u.com熱心網友回復:
- 不要將陣列和指標隱藏在 typedef 后面。這是一個非常非常糟糕的做法。
- 使用指向陣列的指標
int (*matrix)[3] = malloc(3 * sizeof(*matrix));
并用作普通矩陣
matrix[1][2] = 5;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/410344.html
標籤:
下一篇:C蘭德()。生成隨機字串的問題
