Why is it possible to store a string on a char pointer?

Asked

Viewed 123 times

5

Why char stores a single character and the pointer points to its value in memory, so it shouldn’t have just one character? Example:

char *str = "Ola";

Why str does not store only one character?

1 answer

5


The question starts from a wrong premise. It is not storing a string in a pointer of char.

The character string is being stored in a static area of memory, usually the data segment. str is actually storing a pointer to char (4 or 8 bytes according to the architecture), so obviously an address. What address is that? The address where the string starts in the static memory area.

Remembering that all string in C has an extra ending character indicating its end. In this example there are 4 bytes in the static area.

Makes sense now?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.