- 2069 Asar · 3 marks
Arithmetic operations on pointers
Short answer
Allowed: p++, p--, p+n, p-n, q-p (element count), comparisons. Not allowed: addition of two pointers, multiplication, division, float addition. Example: int a[5], *p=a; p++; p+2; q-p gives element difference.
What type of arithmetic operations can be implemented in pointer? Describe with appropriate syntax and examples.
The following arithmetic operations are allowed on pointers:
| Operation | Syntax | Meaning |
|---|---|---|
| Increment / decrement | p++, p-- | Moves to the next / previous element (by sizeof the type) |
| Add an integer | p + n | Address of the n-th element after p |
| Subtract an integer | p - n | Address of the n-th element before p |
| Subtract two pointers | q - p | Number of elements between them (same array only) |
| Comparison | p < q, p == q | Compares addresses (same array) |
Not allowed: adding two pointers, multiplying or dividing a pointer, or adding a float.
#include <stdio.h>
int main(void)
{
int a[5] = {10, 20, 30, 40, 50};
int *p = a, *q = &a[4];
printf("*p = %d\n", *p);
p++; /* next element */
printf("after p++ : *p = %d\n", *p);
p = p + 2;
printf("after p = p + 2: *p = %d\n", *p);
p--;
printf("after p-- : *p = %d\n", *p);
printf("q - p = %ld elements\n", (long)(q - p));
printf("p < q is %d\n", p < q);
return 0;
}
Output:
*p = 10
after p++ : *p = 20
after p = p + 2: *p = 40
after p-- : *p = 30
q - p = 2 elements
p < q is 1
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Accessing array elements using pointer · Computer Programming, chapter 9
- Swap two values using pointers · Computer Programming, chapter 9