#include<stdio.h>
int main()
{
printf("%s\n", "Hello");
printf("%s\n", &"Hello");
return 0;
}
Output :
Hello
Hello
Can anyone explain to me why "Hello"
and &"Hello"
produce the same result?
It is because the string literal is treated as a const char
array. The code is equivalent to writing this:
char array [] = "Hello";
printf("%s\n", array);
printf("%s\n", &array);
This is quite confusing and I think the C FAQ explains it well. That whole chapter about arrays and pointers should be mandatory reading for all C programmers.
Another thing worth of note: optimizers use something call "string pooling", which means that if the compiler encounters the same string literal twice in the souce code, it will store it at the same address. So your code actually just prints the contents of the same memory location twice. To see if string pooling is used, simply run this code:
printf("%p\n", "Hello");
printf("%p\n", "Hello");
It should print the same address twice, as long as the strings are identical. Change one of the strings, and you will get different addresses.