As far as I know , a string literal like "Hello"
is considered a char*
in C and a const char*
in C++ and for both languages the string literals are stored in read-only memory.(please correct me if I am wrong)
#include <stdio.h>
int main(void)
{
const char* c1;
const char* c2;
{
const char* source1 = "Hello";
c1 = source1;
const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
c2 = source2;
}
printf("c1 = %s\n", c1); // prints Hello
printf("c2 = %s\n", c2); // prints garbage
return 0;
}
Why source1 and source2 behave differently ?(compiled with gcc -std=c11 -W -O3)
In this code snippet
{
const char* source1 = "Hello";
c1 = source1;
const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
c2 = source2;
}
source2
is a local character array of the code block that will be destroyed after exiting the block that is after the closing brace.
As for the character literal then it has static storage duration. So a pointer to the string literal will be valid after exiting the code block. The string literal will be alive opposite to the character array.
Take into account that in C the type of string literal "Hello"
is char [6]
. That is the type of any string literal is a non-const character array. Nevertheless you may not change string literals. Opposite to C in C++ character literals have types of const character arrays.