On 22 Jun 2004 04:42:42 -0700,
breyn12345@hotmail.com (Bill Reyn)
wrote:
[color=blue]
>I am a Java programmer, a newbie with c++, struggling a bit...
>Why does the code below return the starting address for an integer
>array, but for a char array it does not return the starting address,
>rather the actual total char array? Where's the address gone for the
>char array pointer? It was OK for the int array.
>Why the contradiction. What's the logic behind all this? Is it just a
>compiler fudge?
>
>
>#include <iostream>
>using namespace std;
>
>int main()
>{
>char l = 's';
> int num[] = {1,2,3,4,5,6,7,8,9,10};
> char* ch = {"Ritchie did this"};[/color]
Braces are not necessary here. Besides, it would be more correct to
declare ch as const char * (why doesn't BCC 5.5.1 give me a warning
here??)
[color=blue]
> cout << " ch is " << ch << " num is " << num << endl ;
> return 0;
>}
>
>output is:
>
> ch is Ritchie did this num is 0012F77C
>Press any key to continue[/color]
The reason lies in the different overloads for operator<< in
std::ostream.
According to the C++ standard, arrays are implicitly changed to
pointers; presumably there is no overload for operator<< which takes
an int*, so the one for void* is used which prints the memory address
of the pointer. The overload for char*, however, prints the contents
of the character array up to the delimiting null byte (which is
implicitly added to a literal string).
The solution is to cast the [const] char* to a [const] void* (an
unsigned int should work, too), i.e.:
cout << " ch is " << reinterpret_cast<void*>(ch) << " num is "
<< num << endl ;
--
Bob Hairgrove
NoSpamPlease@Home.com