Pointer arithmetic
Pointer arithmetic allows user to manipulate memory addresses by performing arithmetic
operations on pointers.
The value of the pointer changes based on the size of the data type it points to.
Importance of pointer arithmetic
Pointer arithmetic improves memory access speed.
It helps manage dynamic memory allocation.
It's necessary for low-level system programming.
Impossible operations in pointer arithmetic
Adding Two Pointers
User can’t add two pointers together. It doesn’t make sense to add memory addresses.
Example (Invalid):
int *p1, *p2;
p1 + p2; // NOT ALLOWED
Multiplying or Dividing Pointers
User can’t multiply or divide pointers.
Example (Invalid):
int *p;
p * 2; // NOT ALLOWED
Subtracting Pointers from Different Arrays
Subtracting pointers is only allowed if both pointers belong to the same array.
Example (Invalid):
int arr1[5], arr2[5];
int *p1 = arr1, *p2 = arr2;
int diff = p1 - p2; // NOT ALLOWED (different arrays)
Possible operations in pointer arithmetic
Add a Number to a Pointer
User can add an integer to a pointer to move it forward by that many elements.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
p = p + 2; // Points to arr[2] (value 30)
Subtract a Number from a Pointer
User can subtract an integer from a pointer to move it backward by that many elements.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[3]; // Points to arr[3] (value 40)
p = p - 2; // Points to arr[1] (value 20)
Subtract Two Pointers
If two pointers point to elements in the same array, you can subtract them to find the
number of elements between them.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p1 = &arr[4]; // Points to arr[4]
int *p2 = &arr[1]; // Points to arr[1]
int diff = p1 - p2; // diff = 3 (4 - 1)
Increment a Pointer
User can use ++ to move a pointer to the next element.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
p++; // Moves to arr[1] (value 20)
Decrement a Pointer
User can use -- to move a pointer to the previous element.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[2]; // Points to arr[2] (value 30)
p--; // Moves to arr[1] (value 20)
Compare Pointers
User can compare pointers using comparison operators (==, !=, <, >, <=, >=) if they point
to elements of the same array.
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p1 = &arr[1];
int *p2 = &arr[3];
if (p1 < p2)
{
printf("p1 points to an earlier element.\n");
}
Program:
#include <stdio.h>
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
int* ptr1 = arr;
int* ptr2 = arr + 2; // ptr2 points to the third element
// Possible operations
printf("Possible operations:\n");
printf("ptr1 + 1 = %p\n", ptr1 + 1);
printf("ptr1 - 1 = %p\n", ptr1 - 1);
printf("ptr2 - ptr1 = %d\n", ptr2 - ptr1); // Output: 2
printf("ptr1 < ptr2 = %d\n", ptr1 < ptr2); // Output: 1 (true)
return 0;
}