fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. int main(){
  6. int i,j,k;
  7. int a,b;
  8. int **mat;
  9. scanf("%d %d",&a,&b);
  10.  
  11. mat = (int**)malloc(a * sizeof(int*));
  12. if (mat == NULL) {
  13. fprintf(stderr, "Memory allocation failed for row pointers.\n");
  14. return 1;
  15. }
  16.  
  17. for(i = 0; i < a; i++){
  18. mat[i] = (int*)malloc(b * sizeof(int));
  19. if (mat[i] == NULL) {
  20. fprintf(stderr, "Memory allocation failed for row %d.\n", i);
  21. for (int l = 0; l < i; l++) {
  22. free(mat[l]);
  23. }
  24. free(mat);
  25. return 1;
  26. }
  27. }
  28.  
  29.  
  30.  
  31. int counter = 1;
  32. for(i = 0; i < a; i++){
  33. for(j = 0; j < b; j++){
  34. mat[i][j] = counter;
  35. counter++;
  36. }
  37. }
  38.  
  39.  
  40. for(i=0;i<a;i++){
  41. for(j=0;j<b;j++){
  42. printf("%d ",mat[i][j]);
  43. }
  44. printf("\n");
  45. }
  46.  
  47.  
  48. for(i = 0; i < a; i++){
  49. free(mat[i]);
  50. }
  51. free(mat);
  52.  
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 5256KB
stdin
2 3
stdout
1 2 3 
4 5 6