fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // 必要があれば変数などを追加してもOKです
  5.  
  6. int main(){
  7. int i, j;
  8. int a, b;
  9. int **mat;
  10.  
  11. scanf("%d %d", &a, &b);
  12.  
  13. // ここで2次元配列の動的確保をする
  14. mat = (int **)malloc(sizeof(int *) * a);
  15. if (mat == NULL) {
  16. printf("ERROR: memory allocation failed\n");
  17. return 0;
  18. }
  19.  
  20. for (i = 0; i < a; i++) {
  21. mat[i] = (int *)malloc(sizeof(int) * b);
  22. if (mat[i] == NULL) {
  23. printf("ERROR: memory allocation failed\n");
  24. return 0;
  25. }
  26. }
  27.  
  28. // ここで2次元配列に数値を代入する(例:i + j)
  29. for (i = 0; i < a; i++) {
  30. for (j = 0; j < b; j++) {
  31. mat[i][j] = i + j;
  32. }
  33. }
  34.  
  35. // 以下の部分は表示の部分です
  36. // いじらなくてOK
  37. for (i = 0; i < a; i++) {
  38. for (j = 0; j < b; j++) {
  39. printf("%d ", mat[i][j]);
  40. }
  41. printf("\n");
  42. }
  43.  
  44. // さて,最後に忘れずにすることと言えば?
  45. for (i = 0; i < a; i++) {
  46. free(mat[i]); // 各行を解放
  47. }
  48. free(mat); // 最後に全体のポインタを解放
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 5280KB
stdin
2 3
stdout
0 1 2 
1 2 3