简体   繁体   中英

what does *(&char_array) mean in C?

I have this C program:

#include <stdio.h>

int main(){

char char_ar[] = "hello world.";
char* char_ptr = char_ar;

/*Same thing*/
printf("*Same thing:\n");
printf("%x : %c\n", &*char_ptr, *char_ptr);
printf("%x : %c\n", &*char_ar, *char_ar);

/*Not same thing*/
printf("*Not the same thing:\n");
printf("%x : %c\n", char_ptr, *char_ptr);
printf("%x : %c\n", &char_ar, *(&char_ar));

getchar();
}

The last printf does not print out "mem_address : h".

Instead, it prints out "mem_address : some_random_char"

What does *(&char_array) in that line do so that it outputs random character?

*(&char_array) is equivalent to char_array . In this case * and & nullify each other's effect.

C11- §6.5.3.2/3:

The unary & operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type". If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue. [...]

Note that you should have use %p instead of %x for pointer data type.

printf("%x : %c\n", char_ptr, *char_ptr);

prints the character that char_ptr points to, which should be 'h'.

printf("%x : %c\n", &char_ar, *(&char_ar));

prints the first byte of the address of char_ptr , interpreted as a character, which should show up as a completely random and unpredictable character.

haccks is absolutely correct that *(&char_ar) is equivalent to char_ar , but I also wanted to add that *(&char_ar) is NOT the same as &*char_ar .

Add these two lines to see the difference:

// This is a char**
printf("%p, sizeof(&*char_ar): %d\n", &*char_ar, sizeof(&*char_ar));

// This is a char*[]
printf("%p, sizeof(*(&char_ar)): %d\n", *(&char_ar), sizeof(*(&char_ar)));

See here for a additional explanation .

Would've posted as a comment, but it would be a bit much with code examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM