A C/C++ Pointer Puzzle?

This C programming puzzle demonstrates how pointer arithmetic works with different types of pointers and multi-dimensional arrays. Understanding pointer sizes and type differences is crucial for mastering pointer arithmetic in C.

Syntax

sizeof(pointer_variable)
(char*)(pointer + 1) - (char*)pointer

Example: Pointer Arithmetic Puzzle

Let's analyze this step-by-step with a complete C program that demonstrates pointer arithmetic with various pointer types −

#include <stdio.h>

int main() {
    int a[4][5][6];
    int x = 0;
    int* a1 = &x;
    int** a2 = &a1;
    int*** a3 = &a2;
    
    /* Print sizes of different variables */
    printf("%ld %ld %ld %ld\n", sizeof(a), sizeof(a1), sizeof(a2), sizeof(a3));
    
    /* Address arithmetic - adding 1 to address of pointers */
    printf("%ld ", (char*)(&a1 + 1) - (char*)&a1);
    printf("%ld ", (char*)(&a2 + 1) - (char*)&a2);
    printf("%ld ", (char*)(&a3 + 1) - (char*)&a3);
    printf("%ld\n", (char*)(&a + 1) - (char*)&a);
    
    /* Pointer arithmetic - adding 1 to pointer values */
    printf("%ld ", (char*)(a1 + 1) - (char*)a1);
    printf("%ld ", (char*)(a2 + 1) - (char*)a2);
    printf("%ld ", (char*)(a3 + 1) - (char*)a3);
    printf("%ld\n", (char*)(a + 1) - (char*)a);
    
    /* Array element address arithmetic */
    printf("%ld ", (char*)(&a[0][0][0] + 1) - (char*)&a[0][0][0]);
    printf("%ld ", (char*)(&a[0][0] + 1) - (char*)&a[0][0]);
    printf("%ld ", (char*)(&a[0] + 1) - (char*)&a[0]);
    printf("%ld\n", (char*)(&a + 1) - (char*)&a);
    
    return 0;
}
480 8 8 8
8 8 8 480
4 24 120 480
4 24 120 480

How It Works

The puzzle demonstrates several key concepts −

  • sizeof() results: The 3D array a[4][5][6] has 120 integers (4×5×6×4 bytes = 480 bytes). All pointers (a1, a2, a3) are 8 bytes on 64-bit systems.
  • Address arithmetic: When we take the address of a pointer (&a1, &a2, &a3) and add 1, we move by the size of the pointer (8 bytes).
  • Pointer arithmetic: When we add 1 to a pointer value, we move by the size of the pointed-to type − 4 bytes for int*, 8 bytes for int**, etc.
  • Array arithmetic: Array names decay to pointers, so a + 1 moves by the size of one complete 2D slice (5×6×4 = 120 bytes).

Key Points

  • Pointer size is constant (8 bytes on 64-bit systems) regardless of what it points to.
  • Pointer arithmetic depends on the pointed-to type, not the pointer size.
  • Multi-dimensional arrays follow nested pointer arithmetic rules.
  • Taking the address of a variable creates a pointer to that variable's type.

Conclusion

This puzzle illustrates the fundamental difference between pointer sizes and pointer arithmetic in C. Understanding these concepts is essential for working with complex data structures and memory management.

Updated on: 2026-03-15T11:38:09+05:30

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements