Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Given an example of C pointer addition and subtraction
Pointer arithmetic is a fundamental concept in C programming that allows you to perform mathematical operations on pointer variables. Two important operations are pointer addition and subtraction, which help navigate through memory addresses.
Syntax
/* Pointer Addition */ new_address = current_address + n; /* Pointer Subtraction */ new_address = current_address - n;
Where n is the number of elements to move, and the actual byte offset is calculated as: n * sizeof(data_type)
C Pointer Addition
Pointer addition involves adding an integer value to a pointer. The result is a new memory address that is offset by n * sizeof(data_type) bytes from the original address.
Example
The following program demonstrates pointer addition −
#include <stdio.h>
int main() {
int num = 500;
int *ptr = # /* pointer to int */
printf("Original address of ptr: %p
", (void*)ptr);
printf("Value at ptr: %d
", *ptr);
ptr = ptr + 3; /* adding 3 to pointer variable */
printf("After adding 3, address of ptr: %p
", (void*)ptr);
printf("Address difference: %ld bytes
", (long)(3 * sizeof(int)));
return 0;
}
Original address of ptr: 0x7fff5fbff6ac Value at ptr: 500 After adding 3, address of ptr: 0x7fff5fbff6b8 Address difference: 12 bytes
C Pointer Subtraction
Pointer subtraction involves subtracting an integer value from a pointer. This moves the pointer backward in memory by n * sizeof(data_type) bytes.
Example
The following program demonstrates pointer subtraction −
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = &arr[4]; /* pointing to last element */
printf("Original address of ptr: %p
", (void*)ptr);
printf("Value at ptr: %d
", *ptr);
ptr = ptr - 2; /* subtract 2 from pointer variable */
printf("After subtracting 2, address of ptr: %p
", (void*)ptr);
printf("Value at new position: %d
", *ptr);
return 0;
}
Original address of ptr: 0x7fff5fbff6b0 Value at ptr: 50 After subtracting 2, address of ptr: 0x7fff5fbff6a8 Value at new position: 30
Key Points
- Pointer arithmetic moves by sizeof(data_type) bytes, not single bytes
- Adding 1 to an
int*moves 4 bytes forward (on most systems) - Use
%pformat specifier for printing pointer addresses - Pointer arithmetic is commonly used with arrays and dynamic memory
Conclusion
Pointer addition and subtraction are essential operations for navigating memory in C. Understanding how pointers move by the size of their data type is crucial for effective memory management and array manipulation.
