cdynamic-memory-allocationmulti-dimensional-scaling

Dynamic array of array of int in C


How can an array of array of int be declared outside the main, then build inside the main once we know the length of the array of array we want to build, if one dimension is already known.

For example, if the array should be array[numberofargs][2], where the dimension 2 is already known but not numberofargs before execution of main.


Solution

  • One way is just to declare for example a pointer in a file scope like

    int ( *array )[2] = NULL;
    

    and then in one of functions allocate a memory for the array. For example

    #include <stdlib.h>
    
    int (*array)[2] = NULL;
    
    int main(void) 
    {
        int numberofargs = 5;
        array = malloc( sizeof( int[numberofargs][2] ) );
    
        //...
        
        free( array );
        
        return 0;
    }
    

    Or the following way

    #include <stdlib.h>
    
    int **array = NULL;
    
    int main(void) 
    {
        int numberofargs = 5;
    
        array = malloc( numberofargs * sizeof( *array ) );
        
    
        for ( int i = 0; i < numberofargs; i++ )
        {
            array[i] = malloc( sizeof( *array[i] ) );
        }
    
        //...
        
        for ( int i = 0; i < numberofargs; i++ )
        {
            free( array[i] );
        }
        free( array );
        
        return 0;
    }