fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(){
  5. int i,j,k;
  6. int a,b;
  7. int **mat;
  8. scanf("%d %d",&a,&b);
  9.  
  10. // 【修正箇所】Step1: 「int型ポインタ」の配列をa個分確保
  11. mat = (int **)malloc(sizeof(int *) * a);
  12. if(mat == NULL)
  13. {
  14. printf("ERROR\n");
  15. return 0;
  16. }
  17.  
  18. // 【修正箇所】Step2: 各行について、int型の配列をb個分確保
  19. for(i = 0; i < a; i++){
  20. mat[i] = (int *)malloc(sizeof(int) * b);
  21. if(mat[i] == NULL){
  22. printf("ERROR\n");
  23. return 0;
  24. }
  25. }
  26.  
  27. k=0;
  28. for(i=0;i<a;i++)
  29. {
  30. for(j=0;j<b;j++)
  31. {
  32. mat[i][j]=k+1;
  33. k++;
  34. }
  35. }
  36.  
  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. }
Success #stdin #stdout 0s 544KB
stdin
2 3
stdout
1 2 3 
4 5 6