RicardasSim

2d array

Oct 26th, 2025
2,043
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main()
  5. {
  6.  
  7.     int num_of_rows = 3;
  8.     int num_of_cols = 4;
  9.  
  10.     // Allocate memory for an array of int pointers
  11.  
  12.     int **p_mtrx = malloc( num_of_rows * sizeof(int *) );
  13.  
  14.     if ( p_mtrx == NULL )
  15.     {
  16.         // If allocation fails, print an error and exit
  17.         printf("Error: failed to allocate memory for p_mtrx.\n");
  18.         return 1;
  19.     }
  20.  
  21.     // Allocate memory for each row and initialize values
  22.  
  23.     for ( int i = 0; i < num_of_rows; ++i )
  24.     {
  25.         p_mtrx[i] = malloc( num_of_cols * sizeof(int) );
  26.  
  27.         if ( p_mtrx[i] == NULL )
  28.         {
  29.             // If allocation fails for a row,
  30.             // clean up previously allocated rows
  31.             printf("Error: failed to allocate memory for p_mtrx row [%d].\n", i);
  32.  
  33.             for ( int j = 0; j < i; ++j )
  34.             {
  35.                 // Free each previously allocated row
  36.                 free( p_mtrx[j] );
  37.             }
  38.  
  39.             // Free the top-level pointer array
  40.             free( p_mtrx );
  41.  
  42.             return 1;
  43.         }
  44.  
  45.         // Fill the row with sample values
  46.         // sequential integers
  47.         for ( int j = 0; j < num_of_cols; ++j )
  48.         {
  49.             p_mtrx[i][j] = i * num_of_cols + j;
  50.         }
  51.  
  52.     }
  53.  
  54.     // Print the contents of the 2D array
  55.     printf("Contents:\n");
  56.  
  57.     for ( int i = 0; i < num_of_rows; ++i )
  58.     {
  59.         for ( int j = 0; j < num_of_cols; ++j )
  60.         {
  61.             printf("%d ", p_mtrx[i][j] );
  62.         }
  63.        
  64.         printf("\n");
  65.     }
  66.  
  67.     // Free all allocated memory
  68.    
  69.     // Free each row
  70.     for ( int i = 0; i < num_of_rows; ++i )
  71.     {
  72.         free( p_mtrx[i] );
  73.     }
  74.  
  75.     // Free the array of row pointers
  76.     free( p_mtrx );
  77.  
  78.     // Exit normal
  79.  
  80.     return 0;
  81. }
  82.  
  83. /*
  84. Output:
  85.  
  86. Contents:
  87. 0 1 2 3
  88. 4 5 6 7
  89. 8 9 10 11
  90.  
  91. */
Advertisement