Open In App

A C/C++ Pointer Puzzle

Improve
Improve
Like Article
Like
Save
Share
Report

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);
}


Output:

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

Related Articles:



Last Updated : 17 Jul, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads