Kumaravel Rajan
Kumaravel Rajan

Reputation: 131

How is a const array able to have only characters in each element but a char* array is able to point to strings in each element?

char characters[] = {'h','e','l','l','o'};


char* characters[] = {"h","e","l","l","o"};

How is the latter able to point to individual strings?

Upvotes: 2

Views: 121

Answers (2)

Geezer
Geezer

Reputation: 5720

How is the latter able to point to individual strings?

When you write this:

char characters[] = {'h','e','l','l','o'};

you define an array of type char, i.e. you have defined a variable of type char[5]. Hence you can initialize it with elements of type char.

In contrast, when you write:

char* characters[] = {"h","e","l","l","o"};

you define an array of type char*, i.e. you have defined a variable of type char*[5] -- and char* means pointer to char, i.e. C style string. Hence you can initialize it with elements of type string literal.

Perhaps the second array should more aptly be named strings[] instead of characters[].

To be precise, string literals such as 'h', are themselves of type const char[2]1, which corresponds in pointer terms to const char*. So an array of such strings should be defined const char* strings[] = ... and not char* strings[] = ....


1 const char[2] and not const char[1] as it is null terminated, as in it's an array holding 1st element to be 'h and 2nd to be '\0'

Upvotes: 3

Ron
Ron

Reputation: 15521

Because of different types. In your first example you have an array of chars, in your second example you have an array of pointers to chars (array of arrays if you want). String literals are of type const char[] which translates to const char*. You should have a const qualifier in your second example:

const char* characters[] = {"h","e","l","l","o"};

It just so happens your string literals have one character in them followed by a hidden null terminating character. So if you had:

const char test[] = "h";

what you actually have is:

const char test[] =  {'h', '\0'};

Add a pointer to the above example and you have an array of null terminated character arrays. To make things more clear you could also have:

const char* characters[] = {"hello","world","etc"};

Prefer std::string to the above approach as it does all the heavy lifting for you.

Upvotes: 1

Related Questions