What does getting the address of an array variable mean?

前端 未结 7 1587
無奈伤痛
無奈伤痛 2020-12-01 09:16

Today I read a C snippet which really confused me:

#include 

int
main(void)
{
    int a[] = {0, 1, 2, 3};

    printf(\"%d\\n\", *(*(&a +         


        
相关标签:
7条回答
  • 2020-12-01 10:10
    *(*(&a + 1) - 1)
    

    is an awkward and dangerous way to address the last element in an array. &a is the address of an array of type int[4]. (&a+1) gives the next int[4] array after the currently addressed one a. By dereferencing it using *(&a + 1) you make it to a *int, and with the additional -1 you point to the last element of a. Then this last element is dereferenced and thus the the value 3 is returned (in your example).

    This works well if the type of the array elements has the same length as the alignment of the target CPU. Consider the case you have an array of type uint8 and length 5: uint8 ar[]={1,2,3,4,5}; If you do the same now (on a 32-bit architecture), you address an unsed padding byte after the value of 5. So ar[5] has an address that is aligned to 4 bytes. The individual elements in ar are aligned to single bytes. I.e., the address of ar[0] is the same as the address of ar itself, the address of ar[1] is one byte after ar (and not 4 bytes after ar), ..., the address of ar[4] is ar plus 5 bytes and thus not aligned to 4 bytes. If you do (&a+1) you get the address of the next uint8[5] array, which is aligned to 4bytes, i.e., it is ar plus 8 bytes. If you take this address of ar plus 8 bytes and go one byte back, you read at ar plus 7, which is not used.

    0 讨论(0)
提交回复
热议问题