ARRAYS

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];


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:

1
2
char *myStr = "This is my string.";
printf("Your str: %s", myStr);


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.
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++.
Last edited on
Topic archived. No new replies allowed.