简体   繁体   中英

What exactly happens when pointers are assigned with strings values during initialization?

I'm quite confused because from what I've learned, pointers store addresses of the data they are pointing to. But in some codes, I see strings often assigned to pointers during initialization.

What exactly happens to the string?
Does the pointer automatically assign an address to store the string and point itself to that address?
How does "dereferencing" works in pointers to strings?

In case of

char *p = "String";

compiler allocate memory for "String" , most likely "String" is stored in read only data section of memory, and set pointer p to points to the first byte of that memory address.

p --------------+
                |
                |
                V
             +------+------+------+------+------+------+------+
             |      |      |      |      |      |      |      |
             | 'S'  | 't'  | 'r'  | 'i'  | 'n'  | 'g'  | '\0' |
             |      |      |      |      |      |      |      |
             +------+------+------+------+------+------+------+
              x100    x101   x102   x103   x104   x105   x106

Q: I see strings often assigned to pointers during initialization.

I think, what you are calling as string is actually a string literal .

According to C11 standard, chapter §6.4.5

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz" . [...]

The representation, "xyz" produces the address of the first element of the string literal which is then stored into the pointer, as you've seen in the initialization time.

Q: Does the pointer automatically assign an address to store the string and point itself to that address?

A: No, the memory for storing the string literal is allocated at compile time by the compiler. Whether a string literal is stored in a read only memory or read-write memory is compiler dependent. Standard only mentions that any attempt to modify a string literal results in undefined behavior .

Q: How does "dereferencing" works in pointers to strings?

A: Just the same way as it happens in case of another pointer to any other variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM