If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, pointer arithmetic allows you to perform mathematical operations on pointers. This can be useful for traversing arrays, manipulating memory, and other tasks.
The basic pointer arithmetic operations are:
ptr++
or ++ptr
increments the pointer by the size of the type it points to.ptr--
or --ptr
decrements the pointer by the size of the type it points to.ptr + n
or ptr - n
increments or decrements the pointer by n
times the size of the type it points to.Here is an example of pointer arithmetic for traversing an array:
Copy code
#include <stdio.h>
int main() {
int a[5] = {1, 2, 3, 4, 5};
int* p = a; // p points to the first element of the array
for (int i = 0; i < 5; i++) {
printf("%d ", *p);
p++; // Increment the pointer to point to the next element
}
printf("\n");
return 0;
}
In this example, the pointer p
is set to point to the first element of the array a
. The for loop iterates 5 times, and in each iteration, it prints the value at the current position of the pointer using the dereference operator (*), then increments the pointer to point to the next element of the array, until it reaches the end of the array.
It's important to mention that, the pointer arithmetic operations only work with pointers that point to elements of an array or a block of memory allocated dynamically, it cannot be used with pointers to single variables or function pointers.
It's also worth noting that, when you increment or decrement a pointer to an array, it doesn't change the actual array, it just changes the position of the pointer, also it's not allowed to increment a pointer over the array's boundary, that could lead to undefined behavior.
Comments: 0