Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

pointers - Multiple Reference and Dereference in C

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
", *&*&*ptr);

getchar();
return 0;
} 

and not this , instead it produces 'd' ?

int main()
{
char *ptr = "hello";
printf("%c
", *&*&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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first program produces h because &s and *s "cancel" each other: "dereferencing an address of X" gives back the X:

  • 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

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
", *ptr);

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
", *&*&ptr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...