[英]C: Accessing (int) via (void *) pointing to (void *) pointing to (int) by typecasting and dereferencing
I'm fiddling around with pointers in C and am still uncertain about some very basics. 我在C中摆弄指针,仍然对一些非常基础的内容不确定。 I came up with the following exemplary code:
我想出了以下示例代码:
#include <stdio.h>
int main(void)
{
int num = 42; // we want to access this integer
void *vptrB = # // pointer B points to the integer
void *vptrA = &vptrB; // pointer A points to pointer B
printf("%d\n", * (int *) * (void **) vptrA);
return 0;
}
The memory should look something like this: 内存应如下所示:
Are there alternatives to access the integer? 有访问整数的替代方法吗? Anything bad/unsafe with the example?
这个例子有什么不好/不安全的地方吗? Is
* (int *) * (void **) vptrA
the only way to access num
via vptrA
and vptrB
? * (int *) * (void **) vptrA
是通过vptrA
和vptrB
访问num
的唯一方法吗?
Are there alternatives to access the integer?
有访问整数的替代方法吗?
int num = 42;
int *vptrB = #
int **vptrA = &vptrB;
// All print 42
printf("%d\n", num);
printf("%d\n", *vptrB);
printf("%d\n", **vptrA);
Anything bad/unsafe with the example?
这个例子有什么不好/不安全的地方吗?
Use of void*
to represent the address to data loses type, alignment, const
and volatile
information. 使用
void*
表示数据的地址会丢失类型,对齐方式, const
volatile
信息。 void*
obliges the use of casting to subsequently interpret the referenced data - this is prone to error. void*
强制使用强制转换来随后解释参考数据-这容易出错。 Although the code is correct in its casting, it is subject to maintenance mistakes and code review mis-understandings. 尽管该代码正确无误,但仍存在维护错误和对代码审查的误解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.