-2

I would really like some help regarding pointers in c++. Take a look at the following code:

int array[3]={4,7,2};
int * a;

a = array;

char Carray[3]={'p','k','\0'};
char * c;

c = Carray;

cout << a << "\n";
cout << c << "\n";

Printing a gives back the address of the first element of the array i.e 4 as expected.

But printing c should have given the address of the first element of Carray i.e p but instead it gives the whole string i.e 'pk' in this case. and we havent used a value operator * here.

It will be very kind if someone can explain this to me

Energya
  • 2,385
  • 2
  • 18
  • 23
salman
  • 27
  • 5

2 Answers2

0

It is because std::cout treats char* as C-style string. If you need the address you can try:

std::cout << (void *) c;
Oblivion
  • 6,731
  • 2
  • 12
  • 32
-1

you should specify how your variables should be treated during the printout. it's not quite obvious when using streams, so I'd recommend to start from the simple things, namely printf :

printf( "%d\n", *a );
printf( "%d\n", a );
printf( "%c\n", *c );
printf( "%s\n", c );

And see what kind of the output you get.

lenik
  • 22,629
  • 4
  • 31
  • 41