C语言中的多重引用和取消引用 [英] Multiple Reference and Dereference in C
问题描述
有人可以为我解释多重引用和取消引用背后的概念吗?为什么以下程序将输出显示为"h"?
Can somebody clealry explain me the concept behind multiple reference and dereference ? why does the following program gives output as 'h' ?
int main()
{
char *ptr = "hello";
printf("%c\n", *&*&*ptr);
getchar();
return 0;
}
不是this,而是产生'd'?
and not this , instead it produces 'd' ?
int main()
{
char *ptr = "hello";
printf("%c\n", *&*&ptr);
getchar();
return 0;
}
我读到连续使用'*'和'&'互相抵消,但此说明不能提供上述代码生成的两个不同输出背后的原因?
I read that consecutive use of '*' and '&' cancels each other but this explanation does not provide the reason behind two different outputs generated in above codes?
推荐答案
第一个程序产生h
,因为&
s和*
s相互取消":取消引用X的地址"会返回X:
The first program produces h
because &
s and *
s "cancel" each other: "dereferencing an address of X" gives back the X:
-
ptr
-指向"hello"
文字的初始字符的指针 -
*ptr
-取消对指向初始字符(即初始字符)的指针的引用 -
&*ptr
指向初始字符的指针(即,指向初始字符的指针,即ptr
本身)的取消引用的地址
ptr
- a pointer to the initial character of"hello"
literal*ptr
- dereference of a pointer to the initial character, i.e. the initial character&*ptr
the address of the dereference of a pointer to the initial character, i.e. a pointer to the initial character, i.e.ptr
itself
以此类推.如您所见,一对*&
将您带回到开始的地方,因此您可以从取消引用/获取地址表达式中消除所有这些对.因此,您第一个程序的printf
等效于
And so on. As you can see, a pair *&
brings you back to where you have started, so you can eliminate all such pairs from your dereference / take address expressions. Therefore, your first program's printf
is equivalent to
printf("%c\n", *ptr);
第二个程序具有未定义的行为,因为正在使用%c
格式说明符将指针传递给printf
.如果将相同的表达式传递给%s
,则会显示单词hello
:
The second program has undefined behavior, because a pointer is being passed to printf
with the format specifier of %c
. If you pass the same expression to %s
, the word hello
would be printed:
printf("%s\n", *&*&ptr);
这篇关于C语言中的多重引用和取消引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!