Pointer Arithmetic in C
Pointer Arithmatic
Pointer arithmetic is a way of performing arithmetic operations on pointers allowing us to move the pointer to different locations in memory.
We can perform the following arithmetic operations on pointers:
Addition: When we add an integer n to a pointer ptr, the result is a new pointer that points to the nth element after the original pointer.
Subtraction: When we subtract an integer n from a pointer ptr, the result is a new pointer that points to the nth element before the original pointer.
Increment: We can increment a pointer ptr by using the ++ operator, which moves the pointer to the next element in the array.
Decrement: We can decrement a pointer ptr by using the -- operator, which moves the pointer to the previous element in the array.
By performing arithmetic operations on pointers, we can traverse arrays, manipulate strings, manipulate binary data, implement complex algorithms, access elements of a dynamic data structure and perform other low-level memory operations in C.
Examples
Example 1 - Access Array Elements
The example below shows how pointer arithmetic can be used to access different elements of an array and move the pointer to different locations in memory.
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element in arr
printf("ptr = %p\n", ptr); // print the address of the first element in arr
printf("*(ptr + 2) = %d\n",
*(ptr + 2)); // print the value of the element 2 positions after ptr
printf("*(ptr++) = %d\n",
*(ptr++)); // print the value of the element that ptr currently
// points to, and then increment ptr
printf("*(++ptr) = %d\n",
*(++ptr)); // increment ptr, and then print the value of the element
// that ptr points to
printf("*(ptr - 2) = %d\n",
*(ptr - 2)); // print the value of the element 2 positions before ptr
return 0;
}
Output:
Explanation
- We declare an array
arr
and a pointerptr
that initially points to the first element inarr
. - We then use pointer arithmetic to access different elements of the array and move the pointer to different locations.
- The first
printf
statement shows the value ofptr
(i.e., the memory address of the first element inarr
). The secondprintf
statement uses pointer arithmetic to access the third element inarr
(i.e.,*(ptr + 2)
is equivalent toarr[2]
). - The next two
printf
statements use the++
operator to increment the pointer and access the next element in the array. - The fourth
printf
statement uses pointer arithmetic to access the third element inarr
again (i.e.,*(ptr - 2)
is equivalent toarr[2]
).
Example 2 - Manipulating strings
Below program shows the use of pointer arithmetic to manipulate a string:
#include <stdio.h>
int main()
{
char str[] = "Hello, World!";
char *ptr = str; // ptr points to the first character in str
printf("Original string: %s\n", str);
// use pointer arithmetic to convert the string to uppercase
while (*ptr != '\0')
{
if (*ptr >= 'a' && *ptr <= 'z')
{
*ptr -= ('a' - 'A');
}
ptr++;
}
printf("Uppercase string: %s\n", str);
return 0;
}
Output:
Explanation
- We declare a character array
str
containing the string "Hello, World!". - We also declare a pointer
ptr
and initialize it to point to the first character instr
. - We then use a
while
loop to traverse the string using pointer arithmetic. - Inside the loop, we check if the current character is a lowercase letter.
- If it is, we use pointer dereferencing to convert it to uppercase by subtracting the difference between uppercase and lowercase letters.
- We then increment the pointer to move to the next character in the string.
- Finally, we print the original and uppercase versions of the string to the console.
- This shows how pointer arithmetic can be used to manipulate strings in C.
When to avoid using pointer Arithmetic
Pointer arithmetic should be avoided when working with non-array variables and objects.
Pointer arithmetic should be avoided when working with pointers that were not initialized.
Pointer arithmetic should not be used to access elements outside the bounds of an array.
Pointer arithmetic should be avoided when working with strings, especially when modifying them. Using string manipulation functions is safer.
Pointer arithmetic should be avoided when working with multi-dimensional arrays. It is often easier and less error-prone to use a nested loop.
Pointer arithmetic should be avoided when working with different pointer types or incompatible pointer types.
Pointer arithmetic should not be used with void pointers, as the size of the pointed-to data is unknown and can result in undefined behavior.