Dynamic array of array of int in C

275 Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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;
}
0
On

Unfortunately, I do not know how to create an array where only the second dimension is known. What you can do is the following:

#include <stdlib.h>
#include <stdio.h>

#define SECOND_DIM 2

int *array;

// returns array[x][y]
int foo(int *array, int x, int y) {
  return *(array+x*SECOND_DIM+y);
}

int main(int args, char *argv[]) {
  if(!argv[0]) return 0;
  
  array = malloc(args*SECOND_DIM*sizeof(int));
  for(int i=0;i<args; i++) {
    for(int j=0;j<SECOND_DIM; j++)
      *(array+(i*SECOND_DIM)+j) = (i+1)*100+j;
  }

  printf("array[0][0]: %d\n", foo(array,0,0)); // array[0][0]
  printf("array[0][1]: %d\n", foo(array,0,1)); // array[0][1]

  free(array);
}
1
On
int (*array)[2] = malloc(sizeof(int[numberofargs][2]));

And then when you're finished with it:

free(array);