Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
Euhi Avatar asked Dec 14 '22 10:12

Euhi


2 Answers

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
like image 164
haccks Avatar answered Mar 23 '23 00:03

haccks


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.

like image 42
Sourav Ghosh Avatar answered Mar 22 '23 22:03

Sourav Ghosh