Explain valid pointer arithmetic and pointer subtraction.
5 marks
Answer in brief
Pointer arithmetic moves between elements of the same array. Its step is measured in elements of the pointed-to type.
Addition and subtraction
If p identifies a[i], p + k can identify a[i + k] when the result is within that array or one past it. p - k moves backwards under the same restriction. p++ updates the pointer to the next element; (*p)++ instead increments the pointed-to value, when that value is writable and the operation is valid.
Pointer difference
Subtracting two suitable pointers into the same array gives their distance in elements, of type ptrdiff_t. The sample sets first to a[0] and last to a[3], so last - first gives 3. Use %td to print ptrdiff_t. The difference must be representable in that type.
One-past-end rule
a + n can be formed for an array of n elements, but it must not be dereferenced. This permits a loop that stops when p equals the end pointer. Do not continue arithmetic beyond that position, even if an unrelated object happens to follow in memory.
Invalid operations
Adding two pointers is not a defined pointer operation.
Do not subtract pointers into unrelated arrays.
Do not assume ordering comparisons between unrelated objects follow their displayed addresses.
Standard C does not support arithmetic on function pointers or void *.
Complexity
A valid pointer step or difference is O(1) in the usual machine model. A loop that advances once per element still takes O(n) time and O(1) auxiliary space. The rules are about array membership, not merely whether an address appears numerically nearby.
Diagram or flowchart
Explain valid pointer arithmetic and pointer subtraction. · Download diagram
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <stddef.h>
int main(void)
{
int a[4] = {10, 20, 30, 40};
int *first = a, *last = a + 3;
printf("Next = %d\n", *(first + 1));
printf("Distance = %td\n", last - first);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Next = 20
Distance = 3
Related exam questions
Related questions in the pointer arithmetic category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.