cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : General C++ Programming : ARRAYS
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programm...
Articles
Lounge
Jobs

-

post  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:

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.
|
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++.
| Last edited on

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2009 - All rights reserved - v2.2
Spotted an error? contact us