Previous | Home | Next |
# Pointer arithmetic in C Programming language
Arithmetic operations on a pointer is possible. There are four arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer (Assuming 32-bit integers) pointer which points to the address 1000.
Let us perform the following arithmetic operation on the pointer:
int *ptr; ptr++;
After above operation, ptr will be point to the next location 1004. The reason behind that, each time ptr incremented and it will located to next integer which is 4 bytes ( i.e. 1004) next to previous location (i.e. 1000). This operation doesn’t impact on actual value at memory location, Means value at memory location not changed.
In case of char:char *ptr; ptr++;
If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001.
# Incrementing a Pointer
#include <stdio.h> const int MAX = 3; int main () { int variable[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = variable; for ( i = 0; i < MAX; i++) { printf("Address of variable[%d] = %x\n", i, ptr ); printf("Value of variable[%d] = %d\n", i, *ptr ); ptr++;/* move to the next location */ } return 0; }
Address of variable[0] = 2d5a5180
Value of variable[0] = 10
Address of variable[1] = 2d5a5184
Value of variable[1] = 100
Address of variable[2] = 2d5a5188
Value of variable[2] = 200
# Decrementing a Pointer
#include <stdio.h> const int MAX = 3; int main () { int variable[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = variable; for ( i = 0; i < MAX; i++) { printf("Address of variable[%d] = %x\n", i, ptr ); printf("Value of variable[%d] = %d\n", i, *ptr ); ptr--;/* move to the next location */ } return 0; }
Address of variable[0] = 6bc7f248
Value of variable[0] = 200
Address of variable[1] = 6bc7f244
Value of variable[1] = 100
Address of variable[2] = 6bc7f240
Value of variable[2] = 10
# Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >.
#include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; ptr = var; i = 0; while ( ptr <= &var[MAX - 1] ) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); ptr++; i++; } return 0; }
Address of var[0] = b0073c40
Value of var[0] = 10
Address of var[1] = b0073c44
Value of var[1] = 100
Address of var[2] = b0073c48
Value of var[2] = 200
Previous | Home | Next |