我拼命嘗試釋放 2d int 陣列,但無法做到。我想當我初始化陣列時有什么問題?你能幫幫我嗎?
int rows = 2;
int cols = 3;
int *mfields = (int *) malloc(sizeof(int) * rows * cols);
int **matrix = (int **) malloc(sizeof(int *) * rows);
for (int i = 0; i < rows; i ) {
matrix[i] = mfields i * cols;
for(int j=0; j<rows;j ) {
matrix[i][j] = (i 1)*(j 1);
}
}
for (int i = 0; i < rows; i ) {
free((matrix[i]));
}
free(matrix);
在此先感謝,克里斯蒂安
uj5u.com熱心網友回復:
分配了兩塊記憶體:
int *mfields = (int *) malloc(sizeof(int) * rows * cols);
int **matrix = (int **) malloc(sizeof(int *) * rows);
因此應該釋放兩塊記憶體:
free(matrix);
free(mfields);
釋放多個記憶體塊,就像這個回圈一樣:
for (int i = 0; i < rows; i ) {
free((matrix[i]));
是不正確的,因為它傳遞的地址free從未從malloc.
通常,將矩陣實作為指向指標的指標并不好。這會阻止處理器進行負載預測并降低性能。如果將與代碼一起使用的 C 實作支持可變長度陣列,那么最好簡單地分配一塊記憶體:
int (*matrix)[cols] = malloc(rows * sizeof *matrix);
如果可變長度陣列支持不可用,則程式應分配一塊記憶體并使用手動計算來尋址陣列元素。雖然這對程式員來說可能是更多的作業,但它對性能更好:
int *matrix = malloc(rows * cols * sizeof *matrix);
for (int i = 0; i < rows; i )
for (int j = 0; j < cols; j )
matrix[i*cols j] = (i 1) * (j 1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/430740.html
上一篇:在C中列印多維陣列
