This question already has an answer here:
-
C: differences between char pointer and array [duplicate]
14 answers
-
What is the difference between char array vs char pointer in C?
7 answers
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?
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 plain char
, signed char
, or unsigned char
), char16_t
array, char32_t
array, or wchar_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.
An array is basically a constant pointer, which points to the beginning of an array. A pointer is just a pointer, which points to any memory location. So given the pointer p
, p[3]
would point to p+3
, which would give a segmentation fault, unless you had declared it as an "array" with at least 4 elements(int *p = new int[4];
). This is exactly the same for int p[4];
, except the fact that p is now a const int *
.