fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(){
  5. int i, j, k;
  6. int rows, cols;
  7. int **mat;
  8.  
  9. scanf("%d %d", &rows, &cols);
  10.  
  11. mat = (int **)malloc(sizeof(int *) * rows);
  12. if(mat == NULL){
  13. printf("ERROR: Failed to allocate memory for rows.\n");
  14. return 0;
  15. }
  16.  
  17. for(i = 0; i < rows; i++){
  18. mat[i] = (int *)malloc(sizeof(int) * cols);
  19. if(mat[i] == NULL){
  20. printf("ERROR: Failed to allocate memory for columns at row %d.\n", i);
  21. return 0;
  22. }
  23. }
  24.  
  25. k = rows * cols;
  26. for(i = 0; i < rows; i++){
  27. for(j = 0; j < cols; j++){
  28. mat[i][j] = k--;
  29. }
  30. }
  31.  
  32. for(i = 0; i < rows; i++){
  33. for(j = 0; j < cols; j++){
  34. printf("%3d ", mat[i][j]);
  35. }
  36. printf("\n");
  37. }
  38.  
  39. for(i = 0; i < rows; i++){
  40. free(mat[i]);
  41. }
  42. free(mat);
  43.  
  44. printf("Memory freed and program ended.\n");
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5264KB
stdin
2 3
stdout
  6   5   4 
  3   2   1 
Memory freed and program ended.