[英]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 pointing to an int pointer. 我有一个指向int指针的void指针。 What is the syntax for properly casting the void pointer when I want to dereference?
当我想取消引用时,正确转换void指针的语法是什么? 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 . 在这里看到这个 。
指向int的指针是*((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 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.