I recently came across the following:
int ( *array )[10] = malloc(...);
Based on my understanding of C's syntax and grammar, this looks like nonsense. It looks like an array is being created (and initialized) with the value of a dereferenced pointer as its identifier.
I understand the idea of pointers to arrays and assigning them blocks on the heap with malloc(), in general, at least. For instance, this makes sense:
int *array = malloc(sizeof (int*) * 10);
...but, the first example looks like gibberish that shouldn't compile. Obviously, I'm missing something.
I feel like I saw whatever this is back when I was learning C, but Googling isn't helping to refresh my understanding. Searches with the terms "pointer", "dereferencing", and "initialization" obviously give results polluted with information on how one keeps track of dereferencing, etc. I'm hoping a human can help me.
This is perfectly legal - you are allocating a pointer to an array of ten integers.
A good way to complete ...
in your malloc
is to use sizeof(*array)
if you need only one array*:
int ( *array )[10] = malloc(sizeof(*array));
For instance, this makes sense:
int *array = malloc(sizeof (int*) * 10);
This is an array of int
s. The first syntax lets you create an array of arrays of int
s - for example
int ( *array )[10] = malloc(50*sizeof(*array));
gives you a 50×10 array.
* Here is a good explanation of why sizeof(*array)
is a good way of sizing your allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With