fork(8) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(){
  5. int i, j;
  6. int a, b;
  7. int **mat;
  8. scanf("%d %d", &a, &b);
  9.  
  10. // 2次元配列の動的確保
  11. mat = (int **)malloc(a * sizeof(int *));
  12. if(mat == NULL){
  13. printf("Memory allocation failed\n");
  14. return 1;
  15. }
  16. for(i = 0; i < a; i++){
  17. mat[i] = (int *)malloc(b * sizeof(int));
  18. if(mat[i] == NULL){
  19. printf("Memory allocation failed\n");
  20. return 1;
  21. }
  22. }
  23.  
  24. // 数値を代入
  25. int k = 1;
  26. for(i = 0; i < a; i++){
  27. for(j = 0; j < b; j++){
  28. mat[i][j] = k++;
  29. }
  30. }
  31.  
  32. // 表示部分(既存コード)
  33. for(i = 0; i < a; i++){
  34. for(j = 0; j < b; j++){
  35. printf("%d ", mat[i][j]);
  36. }
  37. printf("\n");
  38. }
  39.  
  40. // メモリ解放
  41. for(i = 0; i < a; i++){
  42. free(mat[i]);
  43. }
  44. free(mat);
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0.01s 5284KB
stdin
3 2

stdout
1 2 
3 4 
5 6