On Jan 25, 3:45 pm, junw2...@gmail.com wrote:
Quote:
For the code below:
>
char *c = "0113";
unsigned short *p;
p = (unsigned short*)c; //LINE1
std::cout<<"*p: "<<*p<<'\n';
std::cout<<"*c: "<<c<<'\n';
>
The output is:
*p: 12592
*c: 0113
>
Why?
It looks like the program is trying to show that the memory location
where the string is located (p) and the string. It is showing that if
you send a char * (should be const char *) to an IO stream it will
print as a character string. However, if you send a pointer to any
other type to a IO stream it will display the memory location.
The cast in //LINE1 is a nasty hack and you should never do anything
like it. I don't know if the cast itself is UB, but I'm pretty sure
that dereferencing p would be (if I had to guess I would say that the
code was written on a platform where sizeof( unsigned short ) ==
sizeof( char ) == 1). If p were a const void * then it would be
correct, but still not a good thing to do unless forced (normally to
interact with C style code).
Quote:
How does LINE1 work? For the string "0113", there is a implicit '/0' at
the end. How does LINE1 handle it?
It doesn't. c is really a pointer to the memory location that the
string is stored at. The line is simply a way of getting that memory
location pointer into something that can be displayed by the IO stream
as a pointer rather than a string.
The first three lines are reasonable C, but unreasonable C++.
K