C++ string literal type and declaration -
two types of declaration:
char* str1 = "string 1";
and
char str2[] = "string 2";
my compiler doesn't allow me use first declaration error incorrect conversion const char[8] char*. looks okay, version this:
const char* str1 = "string 1";
passed compiler.
please clarify understanding. believed if declare both versions e.g. in main(), first 1 (const char*) - pointer allocated on stack , initialized address in data segment. second version (char[]) - whole array of symbols placed on stack
as far see string literal have const char[] type. using of const char* depricated? c compatibility only?
where each version store string ?
char str2[] = "string 2";
"string 2"
string literal const char[9]
stored in read-only memory.
char str2[]
allocate char array (of size deducted initializer size) in read-write memory.
=
use string literal initialize char array (doing memcpy
of "string 2"
content).
i mean in principle. actual machine code produced optimizations may differ, setting str2
content less trivial means memcpy
string literal.
char* str1 = "string 1";
- here trying actual string literal memory address, 1 const
, shouldn't assign/cast char *
.
const char* str1
should work ok, casting const char[]
const char *
valid (they same thing, unless have access original array size during compilation, pointer variant size-less dumb-down version).
Comments
Post a Comment