Thor
Thor

Reputation: 10068

Printing out the value of pointer to the first index of an char array

I'm new to C++ and is trying to learn the concept of pointer. When I tried to print out the value of pStart, I was expecting its value to be the address of text[0] in hexdecimal (e.g. something like 0x7fff509c5a88). However, the actual value printed out is abcdef.

Could someone explain it to me why this is the case? What parts am I missing?

char text[] = "abcdef";
char *pStart = &text[0]; 
cout << "value of pStart: " << pStart << endl;

Upvotes: 0

Views: 110

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490738

Iostreams provide an overload that assumes a pointer to char points to a NUL-terminated (C-style) string, and prints out the string it points to.

To get the address itself to print out, cast it to a pointer to void instead:

cout << "value of pStsart: " << (void *)pStart << "\n";

Note that you don't really need pStart here at all though. The name of an array (usually, including this case) evaluates to the address of the beginning of the array, so you can just print it directly:

cout << "address of text: " << (void *)text << "\n";

Get out of the habit of using endl as well. It does things you almost certainly don't realize and almost never want.

Upvotes: 3

Related Questions