[英]what does *(&char_array) mean in C?
I have this C program: 我有这个C程序:
#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". 最后一个printf不会打印出“ mem_address:h”。
Instead, it prints out "mem_address : some_random_char" 而是打印出“ mem_address:some_random_char”
What does *(&char_array) in that line do so that it outputs random character? 该行中的*(&char_array)会做什么,以便输出随机字符?
*(&char_array)
is equivalent to char_array
. *(&char_array)
等同于char_array
。 In this case *
and &
nullify each other's effect. 在这种情况下,
*
和&
使彼此的效果无效。
C11- §6.5.3.2/3: 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. 请注意,对于指针数据类型,应使用
%p
而不是%x
。
printf("%x : %c\n", char_ptr, *char_ptr);
prints the character that char_ptr
points to, which should be 'h'. 打印
char_ptr
指向的字符,应为'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. 打印
char_ptr
地址的第一个字节,将其解释为字符,该字符应显示为完全随机且不可预测的字符。
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
. haccks是绝对正确的,
*(&char_ar)
等同于char_ar
,但我还想补充一点, *(&char_ar)
与&*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. 本来可以作为注释发布的,但是对于代码示例来说却有点过多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.