Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of pointers initialized with array of compound literals

I am currently reading the book "Understanding an Using C pointers" and I stumbled on the following example:

int (*(arr1[])) = {(int[]){0,1,2}, (int[]) {3,4,5}, (int[]){6,7,8}}

The author then shows a memory layout for arr1[0][0]…arr1[2][2] and it can be seen that the elements are stored in a contiguous region.

I have two questions regarding this example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. I don’t understand why the first bracket in the declaration of arr1 is necessary, that is, is there a difference to the following declaration:
int *(arr1[]) = ...

I read it as: arr1 is declared as an array containing pointers to ints.

  1. I really don’t understand why the example results in a contiguous block. Because:
    If I initialize an array I write
a = {...}

and list the elements separated by commas. Now, in the preceding example the elements of arr1 should be pointers (unless my understanding of the declaration is wrong). Hence, I would think that for the first member

int *(arr1[])= {(int[]){0,1,2},...

an array containing 0,1,2 is created and its address (this corresponds to the cast to int[]) is then returned and used as the value of the first pointer. However, if that were true, then the numbers 0,1,2 would be located in a potentially separate memory segment from the numbers 3,4,5.

Can someone explain this further?

>Solution :

None of the parenthesis in the declaration int (*(arr1[])) are required. Using int *arr1[] would be equivalent and more readable.

As for the compound literals having consecutive addresses, there’s no requirement for this to be the case. While it would make sense for compound literals (and named variables) declared in the same scope to have addresses in the same general range, the compiler is free to arrange them however it pleases.

When I tried creating the given array and printing the addresses of each element, I got the following:

0x7ffdf47f3880
0x7ffdf47f3890
0x7ffdf47f38a0

So in this particular case the compound literals have increasing addresses yet are not adjacent to each other. There are 4 bytes in between each one, and are therefore not contiguous.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading