# A C/C++ Pointer Puzzle?

CC++Server Side ProgrammingProgramming

Suppose we have one integer variable whose size is 4 byte, another pointer variable is there, whose size is 8 bytes. So what will be the output of the following?

## Example

#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 question, we can follow some important points like below −

• Integer size is 4-byte (32 bit) and pointer size is 8-byte. If we add 1 with pointer, it will point to next immediate type.

• &a1 is of type int**, &a2 is int*** and the &a3 is of type int****. Here all are pointing to pointers. If we add 1, we are adding 8-byte.

• a[0][0][0] is an integer, &a[0][0][0] is int*, a[0][0] is int*, &a[0][0] is of type int(*)[6] and so on. So &a is of type int(*)[4][5][6].

## Output

480 8 8 8
8 8 8 480
4 8 8 120
4 24 120 480
1 4 24 120
Published on 19-Aug-2019 14:15:22