ProgrammingC Developer

Describe the features and pitfalls of pointer arithmetic in the C language. What is this arithmetic based on, what unexpected issues may arise, and how can they be properly avoided?

Pass interviews with Hintsage AI assistant

Answer.

Background:

Pointer arithmetic was introduced in the C language to enable efficient memory manipulation, arrays, and structures. It is closely related to memory addressing and how C operates at the lowest level — adding or subtracting from a pointer allows access to consecutive elements of an array.

Problem:

The main difficulty is that pointer arithmetic is not equivalent to arithmetic with numbers: adding 1 to a pointer increases it by the size of the type it points to. Common mistakes include accessing out of bounds of the allocated array, working with incompatible pointer types, and trying to perform calculations with void *.

Solution:

Always account for the size of the type when working with pointers, avoid arithmetic calculations with void*, and control array boundaries. To access an array element, use indexing or computed pointers while checking boundaries first.

Code example:

#include <stdio.h> int main() { int arr[5] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d\n", *(p + 2)); // 3 // Invalid: p + 10 goes out of bounds of the array return 0; }

Key features:

  • Adding to a pointer increases the address by sizeof(type), not by a byte
  • You can only compare pointers that point to elements of the same array
  • Arithmetic with void* is not allowed (except for some GNU extensions)

Trick questions.

Can you add a float type value or variables of other types to a pointer?

No, you can only add or subtract integer type values to pointers. Using floating point will result in a compilation error.

*Will (arr + i) and arr[i] always return the same result, even if i goes out of bounds of the array?

No. Semantically they are equivalent, but if the index goes out of bounds, both expressions lead to undefined behavior.

What happens when subtracting pointers that refer to different arrays?

The result is not defined by the standard and is considered an error. You can only subtract pointers that are within the same array (or memory allocated in one block).

Common mistakes and anti-patterns

  • Out of bounds access when working with pointers (buffer overrun)
  • Performing arithmetic with void* without explicit casting
  • Using pointers to access memory that has already been freed

Real-life example

In the code, the developer uses pointer arithmetic to traverse an array:

Pros:

  • Faster than indexing on some architectures.

Cons:

  • Forgot to check boundaries — leading to memory corruption (segmentation fault).

In the refactored version, explicit boundary checks are used at each step:

Pros:

  • Guarantees no out of bounds access

Cons:

  • The code became slightly longer and required helper functions to be developed