开发者

Reference to an address?

开发者 https://www.devze.com 2023-01-14 06:44 出处:网络
#include<stdio.h> int main(void) { int arr[3]={1,2,3}; return 0; } Now what will *(&arr) give me and why? I want a detailed explanation. Don\'t just tell me how * and & cancel out开发者
#include<stdio.h>
int main(void) {
int arr[3]={1,2,3};
return 0;
}

Now what will *(&arr) give me and why? I want a detailed explanation. Don't just tell me how * and & cancel out开发者_开发知识库 :P

I want to know how the compiler interprets this expression to give the desired result.


&arr creates a pointer to the array - it's of type int (*)[3], and points at the array arr.

*&arr dereferences that pointer - it's the array itself. Now, what happens now depends on what you do with it. If you use *&arr as the subject of either the sizeof or & operators, then it gives the size or address of the array respectively:

printf("%zu\n", sizeof *&arr);    /* Prints 3 * sizeof(int) */

However, if you use it in any other context, then it is evaluated as a pointer to its first element:

int *x = *&arr;
printf("%d\n", *x);    /* Prints 1 */

In other words: *&arr behaves exactly like arr, as you would expect.


Since arr is a statically-allocated array, not a pointer variable - the expression &arr is equivalent to arr. Hence *(&arr) is actually *arr.

The thing would be different if arr was a pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消