Pointer Arithmetic in Embedded C: Syntax and Examples
In embedded C,
pointer arithmetic means adding or subtracting integers to pointers to navigate memory addresses. This lets you access array elements or hardware registers by moving the pointer to the correct memory location.Syntax
Pointer arithmetic in embedded C involves adding or subtracting integers to a pointer variable. The pointer moves by the size of the data type it points to.
ptr + n: moves pointer forward bynelements.ptr - n: moves pointer backward bynelements.*(ptr + n): accesses the elementnpositions afterptr.
c
int *ptr; // pointer to int ptr = array; // points to first element int value = *(ptr + 2); // access third element
Example
This example shows how to use pointer arithmetic to access and modify elements of an integer array in embedded C.
c
#include <stdio.h> int main() { int data[5] = {10, 20, 30, 40, 50}; int *ptr = data; // pointer to first element // Access elements using pointer arithmetic for (int i = 0; i < 5; i++) { printf("Element %d = %d\n", i, *(ptr + i)); } // Modify third element (index 2) using pointer *(ptr + 2) = 100; printf("After modification:\n"); for (int i = 0; i < 5; i++) { printf("Element %d = %d\n", i, data[i]); } return 0; }
Output
Element 0 = 10
Element 1 = 20
Element 2 = 30
Element 3 = 40
Element 4 = 50
After modification:
Element 0 = 10
Element 1 = 20
Element 2 = 100
Element 3 = 40
Element 4 = 50
Common Pitfalls
Pointer arithmetic can cause bugs if not used carefully:
- Adding or subtracting beyond the array bounds causes undefined behavior.
- Mixing pointer types leads to incorrect address calculations.
- Forgetting that pointer arithmetic moves by the size of the pointed type, not bytes.
Always ensure pointers stay within valid memory ranges.
c
#include <stdio.h> int main() { int arr[3] = {1, 2, 3}; int *p = arr; // Wrong: moving pointer beyond array size // int val = *(p + 5); // Undefined behavior // Correct: stay within bounds int val = *(p + 2); // Access third element safely printf("Value: %d\n", val); return 0; }
Output
Value: 3
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Addition | Move pointer forward by n elements | ptr + n |
| Subtraction | Move pointer backward by n elements | ptr - n |
| Dereference with offset | Access element n positions from pointer | *(ptr + n) |
| Pointer difference | Number of elements between two pointers | ptr2 - ptr1 |
Key Takeaways
Pointer arithmetic moves pointers by the size of their data type, not bytes.
Use pointer arithmetic to access array elements efficiently in embedded C.
Always ensure pointer arithmetic stays within valid memory bounds to avoid errors.
Dereference pointers with offsets to read or modify data at specific positions.
Mixing pointer types or going out of bounds leads to undefined behavior.