What does getting the address of an array variable mean?

前端 未结 7 1605
無奈伤痛
無奈伤痛 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条回答
  •  -上瘾入骨i
    2020-12-01 09:48

    Note that the following is equivalent, but equally nasty:

    printf("%d\n", (&a)[1][-1]);
    

    In this case it is in my opinion more explicit what happens:

    a pointer to the array a is taken

    • the pointer is used as if it were an array: an array of elements like a, i.e. arrays of 4 integers the 1st element of this array is used.

    • Since a is not actually an array, but only one element (consisting of four sub-elements!) this indexes the piece of memory directly after a

    • the [-1] reads the integer directly preceding the memory directly after a, which is the last sub-element of a

提交回复
热议问题