ARRAYS
| G SATISH KUMAR (16) | |||
| case 1: char a[]={'a','b','c'}; cout<<a; //displays abc case 2: int b[]={1,2,3}; cout<<b; //displays address(0x2ff350) of pointer which points to b[0] doubt: every array points to its first element.so when we write cout<<a(or b); it should give address of pointer as in case 2 above.but what is wrong with case 1 why abc is displayed instead of address of a[0]; | |||
| Ganon11 (54) | |||
In C, the only way you could store strings was to have an array of characters. Sometimes this was made with a pointer to a character. So, to make it easier, C allowed you to output char*s directly, like so:
C++ was originally built upon C, so it included this backwards compatibility feature. If you output a character array or character pointer directly, you (should) get the contents of the array as a string rather than the address of a pointer. | |||
| rpgfan3233 (111) | |||
If you cast to a void*, you should be able to retrieve the address using a static_cast:
cout << static_cast<void*>(a);You can also just use the address of the first element:
cout << &a;I personally prefer the first way, but the second way is shorter, and it seems to work for both cases that you presented in C++. | |||
This topic is archived - New replies not allowed.
