Making a pointer point to an element of char array?

Let v be an array of chars, with values "Hello".
If I run the following:

 char v[]="Hello";
 char* p_char= v;
 char* p_char_2 = &v[1];
 cout<<"p_char: "<<p_char<<"\n";
 cout<<"p_char_2: "<<p_char_2<<"\n";
 cout<<"p_char_2 value: "<<*p_char_2<<"\n";

it returns

p_char: Hello
p_char_2: ello
p_char value: e

I’m not sure why, when I add p_char_2 to output stream, I get something like "ello" instead of a memory address…

>Solution :

p_char_2 has type char *, which is the type traditionally used to pass around pointers to strings in C and C++. So the designers of the C++ language decided that when you pass a char * to std::cout << , it prints it as a null-terminated string. That’s just how the language was designed, and it makes it easy to output strings to the standard output.

Leave a Reply