[問題] 動態配置多維陣列降低呼叫malloc次數

看板C_and_CPP (C/C++)作者 (pinchieh)時間16年前 (2009/03/03 10:29), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串1/1
假如我要配置4x5的二維陣列 配置二維本來要呼叫malloc 1+4 = 5次 a = (int**)malloc(4*sizeof(int*)); for(i = 0; i < 4; i++) *a = (int*)malloc(5*sizeof(int)); 參考網路上的資料, 我寫了一個呼叫降為2次, 想問三維以上的要怎麼寫 網路上似乎只找到二維的 #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int **a, i, j; a = (int**)malloc(4*sizeof(int*)); *a = (int*)malloc(4*5*sizeof(int)); for(i = 0; i < 4; i++) *(a+i) = *a + i*5; for(i = 0; i < 4; i++) { for(j = 0; j < 5; j++) { printf("%d ", a[i][j] = i+j); } printf("\n"); } free(*a); free(a); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.98.232

03/03 10:43, , 1F
爬文一下 我記得這個問題常被討論
03/03 10:43, 1F

03/03 13:16, , 2F
可以參考ds中將多維陣列以一維表示
03/03 13:16, 2F
文章代碼(AID): #19h9NwFy (C_and_CPP)
文章代碼(AID): #19h9NwFy (C_and_CPP)