[英]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;
}
內存應如下所示:
有訪問整數的替代方法嗎? 這個例子有什么不好/不安全的地方嗎? * (int *) * (void **) vptrA
是通過vptrA
和vptrB
訪問num
的唯一方法嗎?
有訪問整數的替代方法嗎?
int num = 42;
int *vptrB = #
int **vptrA = &vptrB;
// All print 42
printf("%d\n", num);
printf("%d\n", *vptrB);
printf("%d\n", **vptrA);
這個例子有什么不好/不安全的地方嗎?
使用void*
表示數據的地址會丟失類型,對齊方式, const
volatile
信息。 void*
強制使用強制轉換來隨后解釋參考數據-這容易出錯。 盡管該代碼正確無誤,但仍存在維護錯誤和對代碼審查的誤解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.