C Pointer Arithmetic
Syntax
ptr + n
ptr - n
ptr++
ptr--
Example
#include<stdio.h>
int main(){
int arr[5] = {10,20,30,40,50};
int *ptr = &arr[0];
printf("Element 1: %d\n", *ptr);
ptr++;
printf("Element 2: %d\n", *ptr);
ptr+=2;
printf("Element 4: %d\n", *ptr);
return 0;
}
Output
Element 1: 10
Element 2: 20
Element 4: 40
Explanation
Pointer arithmetic in C allows us to manipulate the address value that a pointer holds. The pointer can be incremented, decremented, or offset by a certain amount of bytes. The pointer arithmetic also allows us to access memory locations based on the value of the pointer.
Use
Pointer arithmetic can be useful in programming tasks like working with data structures such as arrays, strings, and linked lists. The ability to access elements in an array using pointer arithmetic is one of its most common uses. Another use case is when working with memory allocation to allocate memory for large data structures or dynamic memory.
Important Points
- Pointer arithmetic can lead to undefined behavior if not done properly or with uninitialized pointers.
- Pointer arithmetic has the same precedence as the regular arithmetic operators in C.
- Pointer arithmetic does not work with void pointers as they cannot be dereferenced.
- Incrementing a pointer is equivalent to advancing it by one storage unit’s size.
Summary
Pointer arithmetic is an advanced concept in C programming that allows us to manipulate the pointer address values. We can perform basic arithmetic operations on pointers, including incrementing and decrementing them. The pointer arithmetic can be helpful in programming tasks like data structure manipulation, memory allocation, and more. However, it's crucial to use pointer arithmetic with caution and avoid undefined behavior when working with pointers.