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.
You can define the array as follows:
And allocate it like this:
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:
When the array size is known, initialize them:
Define a macro to serve as the array:
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:This has the advantage of automatically adjusting the allocation in case the type used in
MyArray
ever changes.No, it's not possible to create an array like that. You cannot create VLA:s in global space, because globals are static and static objects needs to have their sizes defined at compile time.
What you can do is to use something like this:
Of course,
rows
andcols
needs to be declared and initialized and you should also check if the allocation failed. I'm omitting that here.And yes, you can use
[]
. The bracket operator is just syntactic sugar for pointer aritmetics.a[i]
is the same as*(a+i)
.