Char* can refer to a string of characters?

I was curious on how a char* (variable name) can be set equal to a string of characters demonstrated in the following code line.

 
  char *pName = "John";


From my understanding, char refers to a single character. However, it appears there is something different with char*. Can anybody explain to me why this works?
Thanks in advance!
Read the good free tutorial on this site.

Basically that's known as a c string. An array of many contiguous values of a specific type can be accesed through a pointer. This may hold the address for the first element in the array + index.
It will be able to hold it one at a time though, still like a char.
The characters in a string literal are stored in an array. In your example pName will point to the first character 'J' in the array.

The last element in the array is a null character '\0'. It marks the end of the string. This makes it possible to use the pointer to step through the string until you reach the null character.

When dealing with other types of arrays you normally don't have it null terminated like that, which means you can't step through the array elements without knowing the size, because you don't know when to stop.

This is just a convention. There is nothing stopping you from marking any array with a special value to mark the end of the array.
Thank you all for your much appreciated answers.
I have one more question though. If the character pointer only accesses the address and (since it is a pointer) the value of 'J', how come when I tell the system to do something like this:
1
2
char *pName = "John";
cout << pName;

it outputs to this:
John

Any help would be great! Thank you!

Last edited on
the << operator is overloaded to treat char pointers as if they point to string data.

What it does is it follows the pointer, and prints individual characters from that address until it finds a null terminator character, which marks the end of the string data.

So printing a char pointer works like printing a string.
But printing a char works like printing an individual character.

Example:

1
2
3
4
5
const char* foo = "John";

cout << foo;  // <- printing a char* (a pointer).  << operator will treat it as a string
cout << *foo; // <- printing a char (not a pointer).  Will print a single character, 'J'
cout << foo[0]; // <- same as *foo 
Topic archived. No new replies allowed.