1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
CoffeeRun
  • 71
  • 6
  • 1
    Outside a function you can not do this. – Vlad from Moscow Apr 25 '21 at 15:34
  • Its not possible to statically allocate an array like you mentioned. You will have to dynamically allocate the array inside main. There are multiple ways to do that. Refer this link for more information : https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/ – GustavoS Apr 25 '21 at 15:34
  • What I meant is I want to dynamically allocate the array inside the main, but declare it outside the main. – CoffeeRun Apr 25 '21 at 15:40
  • It was to create global array of pipes which have two ends, (read and write). – CoffeeRun Apr 25 '21 at 15:48

3 Answers3

3

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
cforler
  • 179
  • 1
  • 7
-1
int (*array)[2] = malloc(sizeof(int[numberofargs][2]));

And then when you're finished with it:

free(array);
Dronz
  • 1,970
  • 4
  • 27
  • 50