Suppose we have an integer variable whose size is 4 bytes and another pointer variable whose size is 8 bytes. So what will be the output below?
#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; }
To solve this problem, we can follow some important points:
Integer size is 4 bytes (32 bits), pointer The size is 8 bytes. If we add 1 to the pointer, it will point to the next immediate type.
The type of &a1 is int **, &a2 is int ***, and the type of &a3 is int ****. Here are all pointers. If we add 1, we will add 8 bytes.
a [0] [0] [0] is an integer, &a [0] [0] [0] is int *, a [0] [0] is int * , the type of &a[0][0] is int(*)[6], and so on. So the type of &a is int(*)[4][5][6].
480 8 8 8 8 8 8 480 4 8 8 120 4 24 120 480 1 4 24 120
The above is the detailed content of A C/C++ pointer puzzle?. For more information, please follow other related articles on the PHP Chinese website!