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:
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).
buffer overrun)In the code, the developer uses pointer arithmetic to traverse an array:
Pros:
Cons:
In the refactored version, explicit boundary checks are used at each step:
Pros:
Cons: