假設(shè)我們有一個(gè)整型變量,其大小為 4 字節(jié),還有另一個(gè)指針變量,其大小為 8 字節(jié)。那么下面的輸出會(huì)是什么?
示例
#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; }
登錄后復(fù)制
解決這個(gè)問題,我們可以遵循以下一些重要點(diǎn):
整數(shù)大小為4字節(jié)(32位),指針大小為8字節(jié)。如果我們將1與指針相加,它將指向下一個(gè)立即類型。
&a1的類型是int **,&a2是int ***,&a3的類型是int ****。這里都指向指針。如果我們加1,我們將添加8字節(jié)。
a [0] [0] [0]是一個(gè)整數(shù),&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
登錄后復(fù)制
以上就是一個(gè)C/C++指針謎題?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.xfxf.net其它相關(guān)文章!