Advertisement
dmilicev

function_with_double_pointer.c

Dec 31st, 2019
230
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None
  1. /*
  2.  
  3.     function_with_double_pointer.c
  4.  
  5. https://www.quora.com/How-can-I-pass-to-2-dimensional-int-array-to-M-function-that-receives-M-double-pointer-to-an-int-in-C-language
  6.  
  7.  
  8.     You can find all my C programs at Dragan Milicev's pastebin:
  9.  
  10.     https://pastebin.com/u/dmilicev
  11.  
  12. */
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16.  
  17.  
  18. void print_matrix( char *text, int **M, int r, int c )
  19. {
  20.     int i, j;
  21.  
  22.     printf("%s", text );
  23.  
  24.     for ( i = 0; i < r; i ++ )
  25.     {
  26.         for ( j = 0; j < c; j ++ )
  27.         {
  28.             printf("%2d ", M[i][j] );
  29.         }
  30.  
  31.         putchar('\n');
  32.     }
  33. }
  34.  
  35.  
  36. void input_matrix( char *text, int **M, int r, int c )
  37. {
  38.     int i, j;
  39.  
  40.     printf("%s", text );
  41.  
  42.     for ( i = 0; i < r; i ++ )
  43.     {
  44.         for ( j = 0; j < c; j ++ )
  45.         {
  46.             printf("\n Enter M[%d][%d] = ", i, j );
  47.             scanf("%d", &M[i][j] );
  48.             //printf("\n M[%d][%d] = %2d \n", i, j, M[i][j] );
  49.         }
  50.  
  51.         putchar('\n');
  52.     }
  53. }
  54.  
  55.  
  56. int main(void)
  57. {
  58.     int i, j, r=2, c=2; // r is number of rows, c is number of columns in matrix M[r][c]
  59.  
  60.     int **M = malloc( r * sizeof(*M) );     // Create an array of pointers for r rows
  61.     if ( M == NULL )
  62.     {
  63.         fprintf(stderr, "\n\n malloc() error! \n\n");
  64.         exit(EXIT_FAILURE);
  65.  
  66.     }
  67.  
  68.     for ( i = 0; i < r; i ++ )
  69.     {
  70.         M[i] = malloc( c * sizeof *(M[i]) );// Create M[i] row
  71.         if ( M[i] == NULL )
  72.         {
  73.             fprintf(stderr, "\n\n malloc() error! \n\n");
  74.             exit(EXIT_FAILURE);
  75.         }
  76.  
  77.         for ( j = 0; j < c; j ++ )          // Initialize the elements of the row
  78.         {
  79.             M[i][j] = r * i + j;
  80.         }
  81.     }
  82.  
  83.  
  84.     input_matrix("\n Enter matrix M[r][c] \n", M, r, c );
  85.  
  86.     print_matrix("\n Matrix M[r][c] is: \n\n", M, r, c );
  87.  
  88.  
  89.     for ( i = 0; i < r; i ++ )              // Now clean up
  90.     {
  91.         free( M[i] );                       // Deallocate M[i] row
  92.     }
  93.  
  94.     free(M);                                // Deallocate the array of pointers for r rows
  95.  
  96.     return 0;
  97. }
Advertisement
RAW Paste Data Copied
Advertisement