fork download
  1. #include <stdio.h>
  2. #include <stdlib.h> // malloc, freeを使うために必要
  3.  
  4. int main() {
  5. int rows = 3; // 行数(縦の数)
  6. int cols = 4; // 列数(横の数)
  7.  
  8. // 【Step1のためにまず何を宣言しておくのか?】
  9. // 答え:「int型ポインタ」のポインタ (ダブルポインタ) を宣言します。
  10. int a[3][4];
  11.  
  12. // ==========================================
  13. // これで動的な2次元配列 a[rows][cols] が完成!
  14. // 試しに値を入れて表示してみます。
  15. // ==========================================
  16. for (int i = 0; i < rows; i++) {
  17. for (int j = 0; j < cols; j++) {
  18. a[i][j] = (i + 1) * (j + 1); // 適当な値を代入
  19. printf("%2d ", a[i][j]);
  20. }
  21. printf("\n");
  22. }
  23.  
  24. // ==========================================
  25. // 使い終わったら free() でメモリを解放する
  26. // ==========================================
  27. // ※確保した時と「逆の順番」で解放する必要があります!
  28.  
  29. // 1. 先に各行(Step2で作った中身)を解放する
  30.  
  31.  
  32. // 2. 最後にポインタの配列自体(Step1で作った外枠)を解放する
  33.  
  34.  
  35. return 0;
  36. }
Success #stdin #stdout 0s 5336KB
stdin
Standard input is empty
stdout
 1  2  3  4 
 2  4  6  8 
 3  6  9 12