Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `int ( *array )[10] = malloc(...);` valid C code? [duplicate]

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.

like image 528
CircleSquared Avatar asked May 27 '16 13:05

CircleSquared


1 Answers

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 ints. The first syntax lets you create an array of arrays of ints - 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.

like image 97
Sergey Kalinichenko Avatar answered Nov 08 '22 03:11

Sergey Kalinichenko