C: 通过类型转换和取消引用访问 (int) 通过 (void *) 指向 (void *) 指向 (int)
C: Accessing (int) via (void *) pointing to (void *) pointing to (int) by typecasting and dereferencing
我正在摆弄 C 中的指针,但仍然不确定一些非常基础的知识。我想出了以下示例代码:
#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;
}
内存应该是这样的:
是否有其他方法来访问整数?这个例子有什么 bad/unsafe 吗? * (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?
使用 void*
表示数据地址会丢失类型、对齐方式、const
和 volatile
信息。 void*
强制使用转换来随后解释引用的数据——这很容易出错。尽管代码的转换是正确的,但它容易出现维护错误和代码审查的错误理解。
我正在摆弄 C 中的指针,但仍然不确定一些非常基础的知识。我想出了以下示例代码:
#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;
}
内存应该是这样的:
是否有其他方法来访问整数?这个例子有什么 bad/unsafe 吗? * (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?
使用 void*
表示数据地址会丢失类型、对齐方式、const
和 volatile
信息。 void*
强制使用转换来随后解释引用的数据——这很容易出错。尽管代码的转换是正确的,但它容易出现维护错误和代码审查的错误理解。