Reputation: 750
When I declare a string like that:
char string[] = "Hello";
It is actually equivilant to -
char string[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
So a memory on the stack was allocated for the string by its declaration. But what happens when I declare a string like that:
char *string = "Hello";
The variable 'string' contains the address where the first letter of the string, 'H', is located on memory. I would like to ask:
Where the string is located on memory? stack\heap\etc.
Does enough memory is allocated for the string automatically, or I have to allocate
memory (for example, by malloc
) to the string by myself? And if I have to, how can I do that (I would like to a little example of code)?
I would like to note that there are good chances that the answer for my question is system-dependent. If it is, please note this fact, and try to answer according to what's happens on the popular platforms (Windows, Linux etc).
Upvotes: 2
Views: 346
Reputation: 753665
It isn't defined where the string in char *string = "Hello";
is stored. In practice, it is often in read-only memory called the text segment, where the code of the program is stored. The pointer is stored either on 'stack' or in the data segment, depending on whether the definition is inside a function or outside any function.
You don't have to do anything to allocate memory for the string.
The answer is not system dependent (except that a system may store the string in any convenient location and different systems might store it in different places).
Upvotes: 1