Created: 2023-01-15 12:33
Status: #concept
Subject: Programming
Tags: C Pointer Memory Address Operator
Pointer Arithmetic
p
to an Array’s a
FIRST element?
We can do p = a
or p = &a[0]
because using a
alone "decays" to a pointer to the Memory Address of the first element of an C Array.
j
to a Pointer p
do?
If we add an integer j
to a pointer p
, it shifts the position FORWARD by j
places.
p = &a[i]
p + j = &a[i+j]
p - j = &a[i-j]
q
from another Pointer p
evaluate to?It returns the positional difference (in C Array elements) between the two pointers.
p = &a[i]
q = &a[j]
p - q = i - j
#include <stdio.h>
int main(void)
{
int arr[] = {1,2,4,4,5}, *p, *q;
p = &arr[0];
q = &arr[2];
printf("%d %d %d\n", p-q, p, q);
}
// -2 608172000 608172008
// separated by 4 bytes per integer
Yes, we can use <
, <=
, >
, >=
and ==
, !=
on pointers.
It compares the positions in the array in which the pointers are pointed too.
Using Pointer Arithmetic in Array Traversal
We have to initialize the pointer variable to the pointer of the first position of the array because we cannot modify const C Array pointers
p = &a[0]; p < &a[N]; p++
It has to loop until the max element/boundary of the array. It has to increment the pointer variable by 1, shifting its position by 1 index.
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 12.1