Reputation: 7955
I have some generated C code that looks like this:
char *example[] = {&" ",&"\n", &"\t"};
If I were to write this myself, I would drop the ampersands (&), as string literals are already of type char *
. To me, it looks like example
should have been generated declared as a char**[]
.
Can I be sure that the pointer is the same with or without the &
s? Is this taking the address of an address well defined in C?
Edit: I am investigating a warning on some software currently in a lifecycle that doesn't accept any changes. Is printf("%p", &"hello world");
always the same as printf("%p", "hello world");
, or is this dependent on the compiler?
Upvotes: 2
Views: 159
Reputation: 145829
Is &“string” the same address as “string”?
No, their type is different.
"hello world"
object has type char [12]
. As for other arrays in an expression context, it is converted to char *
.
But:
&"hello world"
has type char (*)[12]
.
So in your example, it also means that:
char *example[] = {&" ",&"\n", &"\t"};
is an invalid declaration as the array elements in the initializer list are not of type char *
.
This is the correct declaration:
char *example[] = {" ", "\n", "\t"};
for the sake of this question, if you had to use the &
, here is the correct declaration:
char (*example[3])[] = {&" ",&"\n", &"\t"};
Upvotes: 7