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)
The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
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 changte string literals. Opposite to C in C++ character literals have types of const character arrays.
const char* source1 = "Hello";
source1
is just pointer on memory-location, where Hello
is defined.
const char source2[] = "Hi";
source2
is local variable of type array of chars and has another address, that string-literal Hi
. After first }
source2 will be destroyed and c2
will be pointed somewhere, but not on location of source2
, so it's just undefined behaviour to dereference c2
after source2
is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With