I have a input stream IPCimstream, which returns a pointer to the character buffer of its stream with dataBuf() function.
Say I have
IPCimstream ims;
What is the difference between printing
1.
cout << ims.dataBuf() << endl;
and
2.
cout << (void*)ims.dataBuf() << endl;
If possible pls explain with an example. Say ims.dataBuf() has “Hello world\n”, etc. or other examples which you feel explain the difference well. Sorry I am new to input stream and I couldnt come up with more interesting examples if there might be any.
Also, what would be the difference if IPCimstream is a character stream vs. binary stream. Thanks.
Well, the difference is that
char*overload ofcout::operator<<treats the pointer as a zero-terminated C string (well, C strings are just char pointers anyway), so it outputs the string itself. If your buffer is not a zero-terminated string, thecout‘s guess is wrong, so it will output some random garbage till the first\0.The
void*version of the same operator doesn’t know what is the object behind the pointer, so everything it can do is just to output the pointer value.You see, this behaviour is not connected with the
IPCimstreamclass, it’s just howcoutworks. (Look at teh example at http://ideone.com/1ErtV).Edit:
In the case if
dataBufcontaining"Hello world\n"thechar*version interprets the pointer as a zero-terminated string. So it will output the characters “Hello world”, output the newline character, and than all the characters that happen to be in the memory after\ntill the next\0. If there is no such character in the memory, the program may just crash. (For language purists: you’ll get undefined behaviour.)The
void*version doesn’t know how to treat the value pointed to by the pointer — so it outputs the pointer value (i.e., the address) itself.Edit 2:
The difference between the character stream and binary stream may be only in the data they hold. In any case, if
dataBuf()returns achar*, thecoutwill output all the characters found in the buffer (and potentially beyond it) until the first\0(or just nothing if\0is at the beginning), and with the cast you’ll get just the buffer’s address output as string.