char **s = &"Is this valid?";
Is obtaining the address at which the address of a string literal is stored allowed in C? I know that the string literal is stored in the .rodata datasegment. However, obtaining the address of that address doesn't make sense.
It should be noted that gcc compiles this and produces a working executable.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
The address of the literal is assembled into the object code of the instruction in which it is used. The constant specified by the literal is assembled into the object code, in the literal pool. A constant is represented by a symbol with a relocatable value. The address of a constant is assembled into the object code.
A string literal is a sequence of zero or more characters enclosed within single quotation marks. The following are examples of string literals: 'Hello, world!' '10-NOV-91' 'He said, "Take it or leave it."'
It's perfectly valid to return a pointer to a string literal from a function, as a string literal exists throughout the entire execution of the program, just as a static or a global variable would.
Your example is not valid:
char **s = &"Is this valid?"; // Not valid, wrong type
This is valid:
char (*s)[15] = &"Is this valid?"; // OK
The type of "Is this valid?"
is char[15]
. The type of a pointer to an array 15 of char
is char (*)[15]
. So the type of &"Is this valid?"
is char (*)[15]
.
The type of a string literal is char[N+1]
where N
is the length of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With