假設我們有一個整數變量,其大小為 4 個位元組,還有另一個指標變量,其大小為 8 個位元組。那麼下面的輸出會是什麼呢?
#include<iostream> using namespace std; main() { int a[4][5][6]; int x = 0; int* a1 = &x; int** a2 = &a1; int*** a3 = &a2; cout << sizeof(a) << " " << sizeof(a1) << " " << sizeof(a2) << " " << sizeof(a3) << endl; cout << (char*)(&a1 + 1) - (char*)&a1 << " "; cout << (char*)(&a2 + 1) - (char*)&a2 << " "; cout << (char*)(&a3 + 1) - (char*)&a3 << " "; cout << (char*)(&a + 1) - (char*)&a << endl; cout << (char*)(a1 + 1) - (char*)a1 << " "; cout << (char*)(a2 + 1) - (char*)a2 << " "; cout << (char*)(a3 + 1) - (char*)a3 << " "; cout << (char*)(a + 1) - (char*)a << endl; cout << (char*)(&a[0][0][0] + 1) - (char*)&a[0][0][0] << " "; cout << (char*)(&a[0][0] + 1) - (char*)&a[0][0] << " "; cout << (char*)(&a[0] + 1) - (char*)&a[0] << " "; cout << (char*)(&a + 1) - (char*)&a << endl; cout << (a[0][0][0] + 1) - a[0][0][0] << " "; cout << (char*)(a[0][0] + 1) - (char*)a[0][0] << " "; cout << (char*)(a[0] + 1) - (char*)a[0] << " "; cout << (char*)(a + 1) - (char*)a; }
解決這個問題,我們可以遵循以下一些重要點:
整數大小為4位元組(32位元),指針大小為8位元組。如果我們將1與指標相加,它將指向下一個立即類型。
&a1的型別是int **,&a2是int ***,&a3的型別是int ****。這裡都指向指針。如果我們加1,我們將添加8位元組。
a [0] [0] [0]是整數,&a [0] [0] [0]是int *,a [0] [0]是int * ,&a [0] [0]的型別是int(*)[6],依此類推。所以&a的型別是int(*)[4] [5] [6]。
480 8 8 8 8 8 8 480 4 8 8 120 4 24 120 480 1 4 24 120
以上是一個C/C++指標謎題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!