# A C/C++ Pointer Puzzle?

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;
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 + 1) - (char*)&a << " ";
cout << (char*)(&a + 1) - (char*)&a << " ";
cout << (char*)(&a + 1) - (char*)&a << " ";
cout << (char*)(&a + 1) - (char*)&a << endl;
cout << (a + 1) - a << " ";
cout << (char*)(a + 1) - (char*)a << " ";
cout << (char*)(a + 1) - (char*)a << " ";
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 is an integer, &a is int*, a is int*, &a is of type int(*) and so on. So &a is of type int(*).

## Output

480 8 8 8
8 8 8 480
4 8 8 120
4 24 120 480
1 4 24 120

Updated on: 19-Aug-2019

150 Views 