char* and char arr[] Difference - C++/C -
this question has answer here:
- c: differences between char pointer , array [duplicate] 14 answers
- char array vs char pointer in c 7 answers
just starting out in c++, wondering if explain something.
i believe can initialise char array in following way
char arr[] = "hello"
this create char array values 'h', 'e', 'l', 'l', 'o', '\0'
.
but if create this:
char* cp = "hello";
will create array, , pointer array?
eg: cp
point first element ('h')
in memory, additional elements of array?
the string literal has array type. in first example gave, there 2 arrays involved. first array containing string literal , second array arr
you're declaring. characters string literal copied arr
. c++11 wording is:
a
char
array (whether plainchar
,signed char
, orunsigned char
),char16_t
array,char32_t
array, orwchar_t
array can initialized narrow character literal,char16_t
string literal,char32_t
string literal, or wide string literal, respectively, or appropriately-typed string literal enclosed in braces. successive characters of value of string literal initialize elements of array.
in second example, letting string literal array undergo array-to-pointer conversion pointer first element. pointer pointing @ first element of string literal array.
however, note second example uses feature deprecated in c++03 , removed in c++11 allowing cast string literal char*
. valid c++11, have instead be:
const char* cp = "hello";
if use conversion char*
in c++03 or in c, must make sure don't attempt modify characters, otherwise you'll have undefined behaviour.
Comments
Post a Comment