Char Pointer Printing

Hello! i dont understand how you can do this:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
  char *pName = "C++";
  
  cout << "pName: " << pName << endl;
  return 0;
}


Why is the adress of the first element in pName not being printed?
and why does it print the whole array?

Hope someone can help with this.

Thanks.
Last edited on
That is the way it works with char*.
If you want to print the address you have to cast it to some other type of pointer - casting
as a pointer to void is the method most people use.
cout << "pName: " << (void*)pName << endl;
Thanks for the answer guestgulkan.

But i still dont understand it full i know that it do it but i dont know why it do it.

the pointer is pointing on the first element.


Thats why i dont understand it.

Last edited on
Part of this is appears to be that you do not quite understand pointers.

pName is a pointer (in this case it is a pointer to char) - so *pName is the object being
pointed to by the pointer - and this is the C character.

so cout << *pName will only print C.

When you do - cout << pName - you are passing the pointer itself. And cin will print out the whole string. In other words it would do cout << *pName, then cout << *(pName+1), until it has stepped through the whole string.
Thank for the answer guestgulkan i know that *pName will print C. I writed wrong
before.

but many thanks guestgulkan now i understand it.

Thanks for the help.
Topic archived. No new replies allowed.