What does getting the address of an array variable mean?

前端 未结 7 1618
無奈伤痛
無奈伤痛 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:06

    &a + 1 will point to the memory immediately after last a element or better to say after a array, since &a has type of int (*)[4] (pointer to array of four int's). Construction of such pointer is allowed by standard, but not dereferencing. As result you can use it for subsequent arithmetics.

    So, result of *(&a + 1) is undefined. But nevertheless *(*(&a + 1) - 1) is something more interesting. Effectively it is evaluated to the last element in a, For detailed explanation see https://stackoverflow.com/a/38202469/2878070. And just a remark - this hack may be replaced with more readable and obvious construction: a[sizeof a / sizeof a[0] - 1] (of course it should be applied only to arrays, not to pointers).

提交回复
热议问题