[英]How to dereference a double void pointer to an int pointer
I have a code that looks somewhat like this: 我有一个看起来像这样的代码:
int num = 5;
int *ptr = #
void **xptr = &ptr;
printf ("values:%d\n",**(int *)xptr);
Why can't i de-reference a void double pointer,which points to an int pointer ? 为什么我不能取消引用一个指向int指针的void双指针? The below two examples work.
以下两个示例起作用。
Snippet:1 片段:1
int *ptr = #
int **xptr = &ptr;
printf ("values:%d\n",**xptr);
Snippet 2: 片段2:
void *ptr = #
printf ("values:%d\n",*(int *)ptr);
The solution is to use both asterics on both sides. 解决方案是在两侧同时使用两个星号。
printf ("values:%d\n",**(int **)xptr);
Why? 为什么? Because otherwise you give the compiler false information about what you are really doing.
因为否则,您会向编译器提供有关您实际操作的虚假信息。 C-style casts can be forced to compile everything, but you must aware yourself: if you force the compiler to do something, then don't blame him to produce probably crash-code.
C样式强制转换可以强制编译所有内容,但您必须了解自己:如果强迫编译器执行某些操作,则不要责怪他生成可能的崩溃代码。
I'd wonder if the compiler didn't generate a warning on that. 我想知道编译器是否不会对此发出警告。 Did it and you ignored the warning?
是否做到了,您忽略了警告?
Keep in mind that your initialization is probably wrong for the xptr
. 请记住,对于
xptr
,您的初始化可能是错误的。 Please see post from haccks here . 请从这里查看吊床的帖子。
void **
is not a generic pointer unlike void *
. 与
void *
不同, void **
不是通用指针。 Any void **
value you play with must be the address of an actual void *
value somewhere. 您使用的任何
void **
值必须是某个地方的实际void *
值的地址。 Compiler should raise a warning for void **xptr = &ptr;
编译器应针对
void **xptr = &ptr;
发出警告void **xptr = &ptr;
: :
[Warning] initialization from incompatible pointer type [enabled by default]
You can do it as follows 您可以按照以下步骤进行操作
int num = 5;
void *ptr = #
void **xptr = &ptr;
printf ("values:%d\n", *((int *)*xptr));
For more detailed explanation, read comp.lang.c FAQ list · Question 4.9 . 有关更多详细说明,请阅读comp.lang.c常见问题列表·问题4.9 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.