Interview Q&A · C · 10 questions in this topic
Arrays & Array Decay — C Interview Q&A
How C arrays really work — decay, sizeof traps, multidimensional layout, and safe passing conventions. Part of Arrays & Strings · 202 questions in the C bank.
What is array-to-pointer decay?
Answer
In most expressions, an array name converts (decays) to a pointer to its first element — losing its size. Exceptions: sizeof, _Alignof, unary & (address of the whole array), and string-literal initializers.
Decay is why functions receive int* plus a separate length: the size information evaporates at the call boundary.
Example
void f(int *p, size_t n); /* size must travel separately */ int a[10]; f(a, sizeof a / sizeof a[0]); /* decay happens at the call */
Why does `sizeof(arr)` work in main but not in a function?
Answer
In the defining scope the name is still an array, so sizeof yields total bytes. Once passed, it decayed to a pointer — sizeof then yields pointer size (8 on 64-bit). The function never saw an array at all.
Conventions: pass (pointer, length) pairs, use sentinel termination where idiomatic, or (C99) sized array parameters for documentation.
Example
/* void g(int a[10]) — 10 is ignored: a is really int* */ void g(int *a, size_t n) { /* use n, never sizeof a */ }
💡 The parameter never was an array is the precise mental model.
How are multidimensional arrays laid out and passed to functions?
Answer
C stores multidimensional arrays contiguously in row-major order. A function parameter must know all dimensions except the first (void f(int a[][COLS])) so it can compute strides — or take a flat pointer plus dimensions and index manually.
Variable-length arrays (C99, optional since C11) allow runtime dimensions with the same row-major math.
Example
#define COLS 4 void sums(int a[][COLS], size_t rows); /* stride needs COLS */ /* flat alternative: void f(int *a, size_t r, size_t c); a[i*c + j] */
💡 All-dimensions-but-first is the parameter rule; row-major is the layout rule.
What are variable-length arrays (VLAs) and why are they controversial?
Answer
VLAs (C99) size automatic arrays at runtime: int buf[n]. They avoid malloc for modest dynamic sizes but live on the stack with no failure reporting — oversized n silently overflows the stack. C11 made them optional, and many style guides (including the Linux kernel) ban them.
Prefer fixed caps plus explicit checks, or malloc with NULL handling, for untrusted sizes.
Example
/* void f(size_t n) { int buf[n]; } // no NULL check possible! */ /* safer: int *buf = malloc(n * sizeof *buf); if (!buf) return -1; */
What is the difference between `int *a[10]` and `int (*a)[10]`?
Answer
int *a[10] is an array of 10 int-pointers (subscript binds first). int (*a)[10] is a pointer to an array of 10 ints (parentheses redirect the binding) — the type that preserves row identity when pointing at 2D rows.
The clockwise/spiral reading rule decodes both: [] and () first, then *.
Example
int *p[10]; /* 10 pointers */ int (*q)[10]; /* one pointer to a 10-int row */ int m[3][10]; q = m; /* q walks whole rows: q+1 skips 10 ints */
How do you safely copy, compare and zero arrays?
Answer
Use memcpy/memmove for copies (memmove for overlap), memcmp for byte comparison, memset for zeroing — with explicit byte counts from sizeof. Raw loops work but invite off-by-one errors; assignment (a = b) is illegal on arrays, and == compares addresses, not contents.
Count in bytes for mem-functions, in elements for loops — mixing the units is the endemic bug.
Example
#include <string.h> int src[4] = {1,2,3,4}, dst[4]; memcpy(dst, src, sizeof dst); /* bytes, not elements */ memset(dst, 0, sizeof dst); /* if (memcmp(dst, src, sizeof dst) == 0) // equal */
How do flexible array members work (struct with `char data[]`)?
Answer
A struct may end with an unsized array (C99): allocate sizeof(struct) + payload, then use data[0..n) as inline storage — one allocation, cache-friendly, no second free. The struct must be dynamically allocated (or be the last member context), sizeof ignores the flex array, and copying needs the full size.
This replaces the old struct-hack (data[1]) with defined behavior.
Example
struct packet { size_t len; unsigned char data[]; }; struct packet *p = malloc(sizeof *p + n); p->len = n; /* p->data[0..n) usable inline */
What is the difference between static, automatic and allocated arrays?
Answer
Static/global arrays live for the program, zero-initialized. Automatic (stack) arrays die at scope exit with indeterminate contents unless initialized. malloc arrays live until free with indeterminate contents (calloc zeroes).
Large or long-lived buffers belong on the heap; small scratch belongs on the stack; shared program state (rarely) is static.
Example
static int table[256]; /* zeroed, program lifetime */ void f(void) { int tmp[64] = {0}; /* stack, explicitly zeroed */ }
Can you return an array from a function?
Answer
Not directly — arrays are not assignable or returnable. Return a pointer instead: to caller-provided storage (safest), to malloc memory with documented transfer, or to static storage (simple but non-reentrant and thread-hostile).
Returning stack-array addresses dangles; static buffers invite clobbering between calls.
Example
/* safe: caller provides */ void fill(int *out, size_t n); /* transfer: callee mallocs, caller frees */ /* int *make(size_t n) { return malloc(n * sizeof(int)); } */
How do you pass arrays safely (bounds, sizes, const)?
Answer
Pass pointer plus element count (never bytes-vs-elements mixed), mark read-only inputs const, and validate indices before use. For fixed-size contracts, C99 static array bounds (void f(int a[static 8])) document minimums the compiler may exploit.
Fortify with _FORTIFY_SOURCE, ASan tests with edge sizes (0, 1, huge), and size_t for all counts.
Example
void sum(const int *a, size_t n); /* const: read-only promise */ /* void kernel(int buf[static 64]); // at least 64, documented */
💡 Pointer plus count plus const is the safe-signature trio.
Recommended resourcesAffiliate links · may earn us a commission