Why would you use a void pointer in this code?
Solution 1:
Because char*
when printed using cout << something
will try to print a string (cout << "Hello, World" << endl;
uses char *
[pedantically, in this example, a const char *
] to represent the "Hello, World"
).
Since you don't want to print a string at address 10000 (it would MOST LIKELY crash), the code needs to do something to avoid the pointer being used as a string.
So by casting to void*
you get the actual address printed, which is the default for pointer types in general, EXCEPT char *
.
Solution 2:
Because otherwise, the overloaded operator << (std::ostream&, const char*)
would be called, which doesn't print an address, but a C-string.
For example:
std::cout << "Boo!";
prints Boo!
, whereas
std::cout << (void*)"Boo!";
prints the address that string literal is located at.