# A C/C++ Pointer Puzzle

• Difficulty Level : Easy
• Last Updated : 17 Jul, 2017

Prerequisite: Pointers
Assuming the size of int = 4 bytes, size of a pointer variable = 8 byte, what will be the output of following program.
Few hints on how to solve it:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

• Size of int = 4 bytes, size of a pointer variable = 8 bytes (on my machine), adding 1 to a pointer makes the pointer point to its next immediate type
• a is of type int (*)
• a1 is of type int *, a2 is of type int **, a3 is of type int **
• &a1 is of type int **, &a2 is of type int ***, &a3 is of type int ****. Since all are pointing to a pointer, therefore adding 1 means adding 8 bytes(sizeof a pointer)
• a is of type int, &a is of type int *, a is of type int *, &a is of type int (*), a is of type int (*), &a is of type int (*), a is of type int (*), &a is of type int (*)

 `// CPP program to illustrate concept ` `// of pointers ` `#include ` `int` `main() ` `{ ` `    ``int` `a; ` `    ``int` `x = 0; ` `    ``int``* a1 = &x; ` `    ``int``** a2 = &a1; ` `    ``int``*** a3 = &a2; ` `    ``printf``(``"%d %d %d %d\n"``, ``sizeof``(a), ``sizeof``(a1), ``sizeof``(a2), ``sizeof``(a3)); ` ` `  `    ``printf``(``"%d "``, (``char``*)(&a1 + 1) - (``char``*)&a1); ` `    ``printf``(``"%d "``, (``char``*)(&a2 + 1) - (``char``*)&a2); ` `    ``printf``(``"%d "``, (``char``*)(&a3 + 1) - (``char``*)&a3); ` `    ``printf``(``"%d \n"``, (``char``*)(&a + 1) - (``char``*)&a); ` ` `  `    ``printf``(``"%d "``, (``char``*)(a1 + 1) - (``char``*)a1); ` `    ``printf``(``"%d "``, (``char``*)(a2 + 1) - (``char``*)a2); ` `    ``printf``(``"%d "``, (``char``*)(a3 + 1) - (``char``*)a3); ` `    ``printf``(``"%d \n"``, (``char``*)(a + 1) - (``char``*)a); ` ` `  `    ``printf``(``"%d "``, (``char``*)(&a + 1) - (``char``*)&a); ` `    ``printf``(``"%d "``, (``char``*)(&a + 1) - (``char``*)&a); ` `    ``printf``(``"%d "``, (``char``*)(&a + 1) - (``char``*)&a); ` `    ``printf``(``"%d \n"``, (``char``*)(&a + 1) - (``char``*)&a); ` ` `  `    ``printf``(``"%d "``, (a + 1) - a); ` `    ``printf``(``"%d "``, (``char``*)(a + 1) - (``char``*)a); ` `    ``printf``(``"%d "``, (``char``*)(a + 1) - (``char``*)a); ` `    ``printf``(``"%d \n"``, (``char``*)(a + 1) - (``char``*)a); ` `} `

Output:

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

Related Articles:

This article is contributed by Subham Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.