Pointers to Pointers (XCode 3.0)

Hello all,

I am newbie in C++ and just started my reviving my C++ (did many years back) again. I've just written a code to understand pointers to pointers, which looks something like below:
#include <iostream>
using namespace std;

int main (int argc, char * const argv[]) {
// insert code here...
char a='z';
char *b;
char **c;
//Now check
cout<<"a is :\t"<<a<<endl;
//b points to a
b=&a;
cout<<"b points a is:\t"<<b<<endl;
//c points pointer b
c=&b;
//Eventually now c has value 'z' which is value of a
cout<<"Ponter c to pointer b is now a is:\t"<<c<<endl;

return 0;
}

Output:
=======

a is : z
b points a is: z
Ponter c to pointer b is now a is: 0xbffff6dc

Everything seems to be fine except the second line. I was expecting some address value (something like 0xbf....) for b which actually points to char a but it outputs z. If I change my pointers type to int everything seems to be look fine and I get an address value for b also. Is it something related with a 'char' pointer type or else. Infact c should also contain value 'z' now.

Any input in this regard will be highly appreciated.

Best,
--PC

the type "char*" is specially treated by cout as being a C-style string. It's what allows you to do this:

1
2
const char* b = "A string";
cout << b;  // this prints "A string", it does not print the address of the string 


If you want to print the address, you'll have to cast it to some other pointer type. Typically, you'd just cast to void*:

 
cout << (void*)b;  // now this will print the address 
Yes, when printing a char pointer it is interpreted as a C string.
For a C string, a char* pointer indicates where the string starts and the string ends with a null character ('\0'). So if right after the z there's a 0 in memory, it will just print the z, otherwise it'll print some garbage or cause a segmentation fault.
You can cast it to some other pointer type to actually print the address (like (void*)b).
Thanks Disch and Athar. I don't think I would have understood this behavior at this point myself. I will make a note of that.

So what what about '**c' , as per my understanding, **c should have now value of 'z'. I changed the code as you suggested and I get output.

a is : z
b points a is: 0xbffff6d8
Ponter c to pointer b is now a is: 0xbffff6dc


Yes, **c would be 'z'.
Oh fine !!! Just modified my code:


1
2
3
	c=&b;
	//Eventually now c has value 'z' which is value of a
	cout<<"Ponter c to pointer b is now a is:\t"<<**c<<endl;


Thanks everybody.
Topic archived. No new replies allowed.