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