A C/C++ Pointer Puzzle
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:
- 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 (*)[5][6]
- 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[0][0][0] is of type int, &a[0][0][0] is of type int *, a[0][0] is of type int *, &a[0][0] is of type int (*)[6], a[0] is of type int (*)[6], &a[0] is of type int (*)[5][6], a is of type int (*)[5][6], &a is of type int (*)[4][5][6]
// CPP program to illustrate concept // of pointers #include <stdio.h> int main() { int a[4][5][6]; 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;[0][0][0] + 1) - (char*)&a;[0][0][0]); printf("%d ", (char*)(&a;[0][0] + 1) - (char*)&a;[0][0]); printf("%d ", (char*)(&a;[0] + 1) - (char*)&a;[0]); printf("%d \n", (char*)(&a; + 1) - (char*)&a;); printf("%d ", (a[0][0][0] + 1) - a[0][0][0]); printf("%d ", (char*)(a[0][0] + 1) - (char*)a[0][0]); printf("%d ", (char*)(a[0] + 1) - (char*)a[0]); printf("%d \n", (char*)(a + 1) - (char*)a); } |
chevron_right
filter_none
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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Double Pointer (Pointer to Pointer) in C
- What is a Pointer to a Null pointer
- 'this' pointer in C++
- C++ | this pointer | Question 4
- C++ | this pointer | Question 1
- C++ | this pointer | Question 2
- C++ | this pointer | Question 3
- NULL pointer in C
- void pointer in C / C++
- Pointer to an Array | Array Pointer
- C++ | this pointer | Question 5
- Opaque Pointer
- Type of 'this' pointer in C++
- Function Pointer in C
- Pointer vs Array in C



