Reputation: 2537
Two types of the declaration:
char* str1 = "string 1";
and
char str2[] = "string 2";
my compiler doesn't allow me to use first declaration with a error incorrect conversion from const char[8] to char*. looks okay, the version like this:
const char* str1 = "string 1";
passed by compiler.
please clarify my understanding. I believed that if we declare both versions e.g. in main(), first one (const char*) - the only pointer will be allocated on the stack and initialized with some address in data segment. second version (char[]) - whole array of symbols will be placed on the stack
as far as I see string literal does now always have a const char[] type. is a using of const char* depricated? for C compatibility only?
where each version will store the string ?
Upvotes: 0
Views: 1469
Reputation: 48918
char* str1 = "string 1";
This is deprecated as of C++98, and is ill-formed as of C++11, as a string literal can't be modified. Modifying it would result in undefined behavior.
To avoid this, the standard prohibits assigning it to a modifiable char
pointer, as it might be modified later on without the programmer realizing that he/she shouldn't have modified it.
char str2[] = "string 2";
Yes, this allocated an array of characters, whereas each character is stored on the stack.
const char* str1 = "string 1";
This isn't deprecated, it is the recommended way (only way) to assign a string literal to a char
pointer. Here, str1
is points to const
chars, i.e. they can't be modified. Thus it is safe to use it somewhere, as the compiler will enforce that the char
s will never be modified.
Here, str1
is stored on the stack, pointing to a string literal, which may or may not be stored in read-only memory (this is implementation defined).
Upvotes: 4
Reputation: 16586
char str2[] = "string 2";
"string 2"
is string literal const char[9]
stored in read-only memory.
char str2[]
will allocate char array (of size deducted from initializer size) in read-write memory.
=
will use the string literal to initialize the char array (doing memcpy
of the "string 2"
content).
I mean in principle. The actual machine code produced with optimizations may differ, setting up str2
content by less trivial means than memcpy
from string literal.
char* str1 = "string 1";
- here you are trying to get the actual string literal memory address, but that one is const
, so you shouldn't assign/cast it to char *
.
const char* str1
should work OK, casting from const char[]
to const char *
is valid (they are almost the same thing, unless you have access to original array size during compilation, then the pointer variant is size-less dumb-down version).
Upvotes: 2