yes,but..

Patrick Head patrick at phead.net
Mon Aug 9 22:01:28 PDT 2004


> #include<iostream>
> using namespace std;
> int main()
> {int arr[3]={1,2};
> cout <<arr<<"\n";
> char ar[3]={'b','y'};
> cout <<ar<<"\n";/*you are still trying to use a char *
> (memory address) as a value to assign to an array, which is NOT allowed
> in C.*/
> return 0;
> }
> which is
>    michael ~ # ./a.out
> 0xbffff750
> by
>   so,after all ar is not an char* but a char[] ,(although arr is an int*  
> )at least as seen by the compiler.Strange,isn't it?Maybe i'm making a  
> salad out of it all,anyway,at least now it works :-)

Michael,

Glad to see you are making heads and tails of all this!!  It's very nice
to see someone so dedicated to learning a language, and doing it by
testing and discussion.

About that last example.  Here is an explanation.  C++ is inherently a
strongly typed language.  It has to be to "understand" objects.  The
cout command in C++ will take the input for any << operator and display
whatever is to the right of the operator.  For char pointers, which
ar[3] ends up being, the language itself knows to actually output the
string it points to.  It does not inherently know what to do with the
int *, so it simply falls back to outputting the address (pointer)
itself.  Classes you define can override the << operator, and therefore
output something more useful.

I hope this helps!

Patrick

 
Patrick Head
patrick at phead.net





More information about the lfs-chat mailing list