[英]How to typecast a void pointer to an int pointer and then store an int in it?
1. void* x;
2. x = new int [10];
3. x = static_cast<int*>(x);
4. *x = 2;
在第4行,我得到: error: 'void*' is not a pointer-to-object type
您需要定義新的指針類型。
您靜態轉換了x,但是由於聲明時x為void *,靜態轉換后類型信息會丟失。
x在他的一生中將始終保持無效*。
這是一個工作代碼示例:
void* x;
int* ptr;
x = new int[10];
ptr = static_cast<int*>(x);
*ptr = 2;
或者,您也可以在同一行中指定和投放:
*(static_cast<int*>(x)) = 2;
由於可以將任何指針(除指向成員的指針和指向函數的指針之外的其他指針,它們完全是其他東西)都隱式轉換為void指針,因此第2行將new int[10]
的結果從int *
隱式轉換為void *
。
同樣,第3行將x
顯式轉換為int *
( static_cast
),其結果隱式轉換回並存儲在x
。 那沒有凈效果。 如果編譯器足夠聰明,它將完全忽略該語句。
您需要做的是引入另一個變量,它是指向int
的指針。
void *x;
x = new int[10];
int *y = static_cast<int *>(x);
*y = 2;
如果您真的想使用沒有任何作為int指針的變量的void指針,請執行此操作。
void *x;
x = new int[10];
*(static_cast<int *>(x)) = 2;
這非常丑陋,只有在特殊情況下才需要。
在實踐中,除非特別需要void指針,否則請完全消除它。
int *x;
x = new int[10];
*x = 2;
無需費力地進行任何顯式類型轉換的事實也使這種錯誤的發生率也降低了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.