Pointer arithmetic in C programming involves performing arithmetic operations on pointers.
Pointers in C are variables that store memory addresses.
They are often used to store the address of another variable, allowing direct access to that variable's memory location.
Here are some operations and rules regarding pointer arithmetic in C:
Pointers can be incremented and decremented, and the size of the increment or decrement depends on the data type the pointer is pointing to.
#include <stdio.h> int main() { int arr[] = {11, 22, 33, 44, 55}; int *ptr = arr; // Pointer to the first element of the array // Incrementing pointer printf("Incrementing pointer\n"); printf("Value at ptr: %d\n", *ptr); // Output: 11 ptr++; // Move to the next element printf("Value at ptr after increment: %d\n", *ptr); // Output: 22 // Decrementing pointer printf("\nDecrementing pointer\n"); ptr--; // Move back to the previous element printf("Value at ptr after decrement: %d\n", *ptr); // Output: 11 return 0; }
Pointers can be subtracted from each other to find the difference in their addresses.
#include <stdio.h> int main() { int arr[] = {11, 22, 33, 44, 55}; int *ptr = arr; // Pointer to the first element of the array // Pointer subtraction printf("\nPointer subtraction\n"); int *ptr2 = &arr[3]; // Pointer to the fourth element ptr2--; // Move to the third element ptr--; // Move to the first element int diff = ptr2 - ptr; // Difference in pointers printf("Difference in pointers: %td\n", diff); // Output: 3 return 0; }
The result will be in terms of the number of elements (of the pointed-to type) between the two addresses.
#include <stdio.h> int main() { int arr[] = {11, 22, 33, 44, 55}; int *ptr = arr; // Pointer to the first element of the array // Accessing array elements using pointer arithmetic printf("\nAccessing array elements using pointer arithmetic\n"); ptr = arr; // Reset pointer to the first element printf("Third element of array: %d\n", *(ptr + 2)); // Output: 33 return 0; }
#include <stdio.h> int main() { int arr[] = {11, 22, 33, 44, 55}; int *ptr = arr; // Pointer to the first element of the array // Multiplication and Division printf("\nMultiplication and Division\n"); ptr = arr; // Reset pointer to the first element ptr = ptr + 2; // Move the pointer two elements forward printf("Value at ptr after moving two elements forward: %d\n", *ptr); // Output: 33 ptr = ptr - 1; // Move the pointer one element backward printf("Value at ptr after moving one element backward: %d\n", *ptr); // Output: 22 return 0; }
Pointers can be used to access elements of an array using pointer arithmetic.
Multiplying or dividing a pointer by an integer results in a pointer offset by a certain number of elements.