char* and char arr[] Difference - C++/C
The string literal itself has array type. So in the first example you gave, there are actually two arrays involved. The first is the array containing the string literal and the second is the array arr
that you're declaring. The characters from the string literal are copied into arr
. The C++11 wording is:
A
char
array (whether plainchar
,signed char
, orunsigned char
),char16_t
array,char32_t
array, orwchar_t
array can be initialized by a narrow character literal,char16_t
string literal,char32_t
string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces. Successive characters of the value of the string literal initialize the elements of the array.
In the second example, you are letting the string literal array undergo array-to-pointer conversion to get a pointer to its first element. So your pointer is pointing at the first element of the string literal array.
However, note that your second example uses a feature that is deprecated in C++03 and removed in C++11 allowing a cast from a string literal to a char*
. For valid C++11, it would have to instead be:
const char* cp = "Hello";
If do use the conversion to char*
in C++03 or in C, you must make sure you don't attempt to modify the characters, otherwise you'll have undefined behaviour.
AJ9
Updated on June 04, 2022Comments
-
AJ9 about 2 years
Just starting out in C++, I was wondering if someone could explain something.
I believe you can initialise a char array in the following way
char arr[] = "Hello"
This will create a Char array with the values
'H', 'e', 'l', 'l', 'o', '\0'
.But if I do create this:
char* cp = "Hello";
Will that create an array, and the pointer to that array?
Eg:
cp
will point to the first element('H')
in memory, with the additional elements of the array? -
Daniel Fischer about 11 yearsThe question is also tagged C, so you may add that in C,
char*
is perfectly valid (although, since attempting to modify string literals invokes undefined behaviour, usingconst char*
has advantages also in C). -
Joseph Mansfield about 11 years@DanielFischer I should look at the tags more. Thanks.
-
AJ9 about 11 yearsWould the second example allow you to edit the contents of the pointed to array? Eg: cp = "Apple". I was unsure if the array would be generated automatically, thanks for the response!
-
Joseph Mansfield about 11 years@Pillbox No. If you attempt to modify the array, you'll have undefined behaviour. String literals are typically stored as read-only.
-
Daniel Fischer about 11 years@Pillbox But
cp = "Apple";
wouldn't change the contents of the array, it would change which array's initial elementcp
points to. Socp = "Apple"; cp = "Banana";
is okay.cp[0] = 'x';
would invoke undefined behaviour. -
Joseph Mansfield about 11 years@DanielFischer You're noticing lots of things that I'm not. Thanks.
-
Suraj Jain over 7 yearswould
int*b = {1,2,3}
work?