Katkat

Reason About C Pointer and Array Declarations

CiscoSoftware Engineer · Technical Screen

Last updated

This question tests the ability to parse complex C declarations and understand memory layout, pointer arithmetic, and the differences between pointers and arrays.

The Pointer-Array Challenge

In C programming, the syntax for declarations can be ambiguous due to operator precedence. Explain the difference between the following two declarations and provide a code snippet demonstrating how to access an element in each:

  1. int *arr[5];
  2. int (*ptr)[5];

Requirements

  1. Describe the type of arr and ptr in each case.
  2. Write a code example showing how to initialize both and how to increment them to point to the next 'element'. Explain what address offset occurs in each case when you perform arr + 1 versus ptr + 1.
  3. Discuss how these structures behave when passed to a function: void func(int *arr[]) vs void func(int (*ptr)[5]).

Constraints

  • Assume a 64-bit architecture where sizeof(int) is 4 bytes.
  • Focus on the memory layout and the pointer arithmetic differences.

Example

// For int *arr[5]
// arr is an array of 5 pointers to int.
// arr + 1 points to the second element in the array of pointers.

// For int (*ptr)[5]
// ptr is a pointer to an array of 5 integers.
// ptr + 1 points to the address exactly 5 * sizeof(int) bytes away.

Hints

Hint 1

Remember that the subscript operator `[]` has higher precedence than the pointer indirection operator `*`.

Hint 2

Think of `int *arr[5]` as an array of objects, whereas `int (*ptr)[5]` is a single pointer pointing to a block of memory.

Hint 3

Consider the difference between a pointer that moves by the size of a single integer pointer versus a pointer that moves by the size of the entire array of integers.

Follow-up questions

  • How does the `const` qualifier change the meaning if written as `int * const ptr[5]` versus `const int *ptr[5]`?
  • If you have a 2D array `int matrix[3][5]`, which of the two declarations above can be used to point to the first row of that matrix?
  • Why is it generally safer to use `size_t` when performing pointer arithmetic or indexing into these structures?