#include <iostream> using namespace std; int main() { char *pc; int *pi; double *pd; pc = (char *)10000; pi = (int *)10000; pd = (double *)10000; // 1) cout << "before pc = " << (void *)pc << " pi = " << pi << " pd = " << pd << endl; pc++; pi++; pd++; // 2) cout << "after increase pc = " << (void *)pc << " pi = " << pi << " pd = " << pd << endl; return 0; }
In this code(1, 2), why is variable pc
cast to a void pointer?
I am checking that a run-time error does not occur if you do not print the variable pc
.
In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal.
Void pointers in C programming are the pointer variables which has no specific data type. These are also called as Generic pointers because it can point to any data type. In General, the compiler has no idea what type of object a void Pointer really points to.
The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.
Example of pointer in Cint a=5; int* point = &a; // pointer variable point is pointing to the address of the integer variable a! int a=5; int* point = &a; // pointer variable point is pointing to the address of the integer variable a!
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.
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 *
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With