Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...