How to cast a void pointer to a pointer when dereferencing?
int x = 5;
int *xPtr = &x;
void **xPtrPtr = &xPtr;
printf("%d\n", *(int*)*xPtrPtr);
I have a void pointer po开发者_高级运维inting to an int pointer. What is the syntax for properly casting the void pointer when I want to dereference? The above code quits with:
error: invalid conversion from ‘int**’ to ‘void**’
Thank you!
For void pointers, you don't really need to know how many indirections there are.
#include <iostream>
int main(void){
int x = 5;
int* pX = &x;
void* pV = &pX;
std::cout << "x = " << **(int**)pV << std::endl;
// better use C++-Style casts from the beginning
// or you'll be stuck with the lazyness of writing the C-versions:
std::cout << "x = " << **reinterpret_cast<int**>(pV) << std::endl;
std::cin.get();
}
Output:
x = 5
x = 5
See this here.
The pointer to int is *((int **)xPtrPtr)
void **xPtrPtr = (void**)&xPtr;
int x = 5;
int *xPtr = &x;
void **xPtrPtr = reinterpret_cast<void**>(&xPtr);
int y = **reinterpret_cast<int**>(xPtrPtr);
cout << y;
Compile: No Error. No Warning!
Output:
5
Code at ideone : http://www.ideone.com/1nxWW
This compiles correctly:
#include <stdio.h>
int main(int argc, char *argv[]) {
int x = 57;
int *xPtr = &x;
void **xPtrPtr = (void**)&xPtr;
printf("%d\n", *((int*)*xPtrPtr));
}
精彩评论