fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(void) {
  5. int rows = 3; // 行数
  6. int cols = 4; // 列数
  7. int i, j;
  8.  
  9. // --- Step 1: ポインタの配列(行)を確保 ---
  10. int **a = (int **)malloc(sizeof(int *) * rows);
  11. if (a == NULL) return 1;
  12.  
  13. // --- Step 2: 各行に実データ(列)の領域を確保 ---
  14. for (i = 0; i < rows; i++) {
  15. a[i] = (int *)malloc(sizeof(int) * cols);
  16. if (a[i] == NULL) return 1;
  17. }
  18.  
  19. // 値の代入と表示の例
  20. for (i = 0; i < rows; i++) {
  21. for (j = 0; j < cols; j++) {
  22. a[i][j] = i * cols + j;
  23. printf("%2d ", a[i][j]);
  24. }
  25. printf("\n");
  26. }
  27.  
  28. // メモリの解放(確保と逆の順番で解放する)
  29. for (i = 0; i < rows; i++) {
  30. free(a[i]); // Step 2で確保した分を解放
  31. }
  32. free(a); // Step 1で確保した分を解放
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
 0  1  2  3 
 4  5  6  7 
 8  9 10 11