Search code examples
carraysinitialization

Creating a static global, variable length 2D array


I am trying to create an array with the following requirements:

  • internal linkage (static global)
  • size only known at runtime
  • elements accessed using the [][] syntax
  • stored on the heap

I have been using the following code to create a VLA which meets almost of my requirements, but this array is limited to the current scope rather than having internal linkage.

int (*array_name)[columns] = malloc( sizeof(int[rows][columns]) );

Is there any way to create an array which meets all of my needs?


Edit - "static global" is an incorrect term for this type of variable scope, "internal linkage" is correct. Please look at the comments to this question for an explanation.


Solution

  • The requested properties can be accomplished as described below. (This is not a recommendation to do so.)

    Define a base pointer and an array size:

    static void *MyArrayPointer;
    static size_t Columns;
    

    When the array size is known, initialize them:

    Columns = some value;
    MyArrayPointer = malloc(Rows * Columns * sizeof(int));
    if (!MyArrayPointer) ... Handle error ...
    

    Define a macro to serve as the array:

    #define MyArray ((int (*)[Columns]) MyArrayPointer)
    

    Once the above is complete, the array may be accessed as MyArray[i][j].

    Note that variable length array support is optional in C. GCC and Clang support them. Given the example shown in the question, we presume variable length array support is available.

    Also, I would be tempted to write the malloc code:

    MyArrayPointer = malloc(Rows * sizeof *MyArray);
    

    This has the advantage of automatically adjusting the allocation in case the type used in MyArray ever changes.