KatInterview

C Declaration Syntax: Arrays of Pointers vs Pointers to Arrays

BehavioralModel answer
EasyModel answerBehavioralcpointersmemory-layout

Last updated

Distinguish between an array of pointers and a pointer to an array in C, explaining their memory layouts and pointer arithmetic behavior.

Understanding C Declaration Syntax

C's declaration syntax can be confusing because of operator precedence rules. Consider these two declarations:

int *arr[5];
int (*ptr)[5];

Your task is to explain the fundamental differences between these constructs.

What You Should Cover

  1. Type Analysis: Describe what arr and ptr actually represent. What types do they have?

  2. Memory Layout and Arithmetic: Show how to initialize both constructs with example data. When you compute arr + 1 versus ptr + 1, what address offset occurs in each case? Explain the underlying reason for the difference.

  3. Function Parameters: Compare the behavior when these types are passed to functions. How does void func(int *arr[]) differ from void func(int (*ptr)[5])? What information is preserved or lost?

  4. Code Example: Provide working C code that demonstrates initialization, element access, and iteration for both declarations.

Assumptions

  • Target platform is 64-bit where pointers are 8 bytes and sizeof(int) is 4 bytes.
  • Emphasize the memory organization and how pointer arithmetic works for each type.

Expected Depth

Your answer should include concrete examples, explain the declaration reading rules, show the memory layout differences, and discuss common mistakes developers make with these constructs.

Hints

Hint 1

Start by parsing each declaration from the identifier outward, remembering that [] binds more tightly than * unless parentheses override precedence.

Hint 2

For pointer arithmetic, remember that adding 1 to a pointer advances by the size of the pointed-to type, not always by one byte.

Hint 3

When arrays are passed as function parameters, they decay to pointers, but pointers to arrays preserve their dimension information.