0
考慮下面的代碼片斷:C++雙PTR到長的ptr轉換
double * p = new double[16];
int value = 1;
void * q = p;
*((double *)q) = value;
int x = ((long *)p)[0];
cout << "Value of x for double * to long * = " << x << endl;
*((int *)q) = value ;
x = ((long *)p)[0];
cout << "Value of x for int * to long * = " << x << endl;
這裏的輸出分別爲0和1。任何人都可以向我解釋爲什麼?
此外,如果我直接訪問指針值...即。 p [0],這兩種情況下的值都正確顯示爲1。爲什麼?
所有這些類型轉換都被視爲代碼異味。不要在真實的代碼中使用。 – iammilind
這基本上是'reinterpret_cast'。該標準不能保證你甚至可以得到什麼結果(即從有效的結果)。 –