Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addressing the address of a string literal in C

Tags:

c

string

literals

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.

like image 644
seininn Avatar asked Mar 31 '12 19:03

seininn


People also ask

What is a string literal in C?

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.

What will be the address of literals?

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.

What is string literal with example?

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."'

Can you return a string literal in C?

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.


1 Answers

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.

like image 178
ouah Avatar answered Oct 22 '22 10:10

ouah