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]
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


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.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.