In a C programming, we can also perform arithmetic operations with pointer.
There are four arithmetic operators that can be performed with pointers:
- Increment (++)
- Decrement ( — )
- Addition ( + )
- Subtraction ( – )
For a simple variable
int a=3;
a++; //print 4
Increment integer value by one.
Pointer is a variable which can hold the address of another variable in above code
For pointer
int a=3;
int *ptr;
ptr=a;
ptr++; //increment by one integer address space
pointer variable address value are incremented based on type of values it holds
Increment a Pointer
Example: Write a program in c language, to increments the variable pointer to access each succeeding element of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> int main () { int arr[] = {10, 20, 30}; int i, *ptr; ptr = arr; //assign the stsrting array address to pointer variable pointer for ( i = 0; i < 3; i++) { printf("\n Address of arr[%d] = %d", i, ptr ); printf("\n Value of arr[%d] = %d", i, *ptr ); ptr++; // move to the next location } return 0; } |
OUTPUT
1 2 3 4 5 6 | Address of arr[0] = -908782628 Value of arr[0] = 10 Address of arr[1] = -908782624 Value of arr[1] = 20 Address of arr[2] = -908782620 Value of arr[2] = 30 |
In above program we can also decrements the pointer.
In above program you have to loop in decrement way as below
1 2 3 4 5 6 | for ( i = 2; i >=0; i--) { printf("\n Address of arr[%d] = %d", i, ptr ); printf("\n Value of arr[%d] = %d", i, *ptr ); ptr--; // move to the previous location } |
1 2 3 4 5 6 | Address of arr[2] = 857698604 Value of arr[2] = 10 Address of arr[1] = 857698600 Value of arr[1] = -1252756080 Address of arr[0] = 857698596 Value of arr[0] = 32765 |