Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading