Advanced C Programming: Pointer Arithmetic, 2D Array Decay, Struct Padding & Bitwise Traps
Clockwise/Spiral C declaration rule, &a vs a+1 pointer scaling, 2D array row pointers, structure alignment padding vs union size, static persistence, and sequence-point undefined behavior.
1. The #1 GATE CS Pointer Trap: a, &a, *a on 1D & 2D Arrays
Suppose int a[5] = {10, 20, 30, 40, 50}; starts at address 1000 with sizeof(int) = 4:
| Expression | C Static Type | Numerical Address / Value | Why? |
|---|---|---|---|
a | int * (decayed) | 1000 | Points to element a[0] (step size = 4 bytes) |
a + 1 | int * | 1004 | Advances by 1 * sizeof(int) = 4 bytes |
&a | int (*)[5] | 1000 | Points to the entire 5-int array (step size = 20 bytes!) |
&a + 1 | int (*)[5] | 1020 | Advances past the whole array: 1000 + 5 * 4 = 1020! |
#include <stdio.h>
int main(void) {
int a[5] = {10, 20, 30, 40, 50};
int *p = (int *)(&a + 1);
printf("%d %d\n", *(a + 1), *(p - 1)); // Prints: 20 50
return 0;
}
2. Complex Declarations, const Pointers & Function Pointers
const int *p(orint const *p): Pointer to constant int —pcan move (p++valid),*p = 5is compile error.int * const p: Constant pointer to int —*p = 5valid,p++is compile error.int (*fp)(int, int): Pointer to a function taking(int, int)and returningint(vsint *fp(int, int)which is a function returningint*!).
3. struct Alignment Padding vs union Memory Sharing
On a 64-bit / 32-bit natural alignment ABI where char = 1B, short = 2B, int = 4B, double = 8B:
- Every member sits at an offset divisible by its own alignment, and
sizeof(struct)is padded to a multiple of the largest member alignment!struct S1 { char a; int b; char c; };1 + 3(pad) + 4 + 1 + 3(tail pad) = 12 bytes!- Reordering
struct S2 { int b; char a; char c; };4 + 1 + 1 + 2(tail pad) = 8 bytes!
union: All members share offset0;sizeof(union)equals the largest member rounded up to max alignment. Used to detect Little-Endian vs Big-Endian byte order!
Short-Circuit Side-Effect Trap in GATE C Code: In int x = 0, y = 1; if (x && ++y), because x is 0, && short-circuits and ++y is NEVER executed (y remains 1)! Similarly, sizeof(i++) is evaluated at compile time (except VLAs), so i is NOT incremented!
Practice Questions on This Chapter (3)
What integer value is printed by the following C program?
#include <stdio.h>
int f(int n) {
static int r = 0;
if (n <= 0) return 1;
if (n > 3) {
r = n;
return f(n - 2) + 2;
}
return f(n - 1) + r;
}
int main(void) {
printf("%d", f(5));
return 0;
}
In C, let int A[4][5] be stored in Row-Major order starting at base memory address 1000 with sizeof(int) = 4 bytes. What are the numerical address values of (A + 2) and (&A + 1) respectively?
Consider the C snippet int x = 0, y = 5, z = 10; int k = (x && ++y) || (z++ && ++x);. What is the value of y + z + x + k after execution?