The pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
Arithmetic operations possible on pointer in C language :
- Increment.
- ecrement.
- Addition.
- Subtraction.
Increment :
- Incrementing a pointer is used in array because it is contiguous memory location.
- Increment operation depends on the data type of the pointer variable.
The formula of incrementing pointer is given below :
new_address= current_address + i * size_of(data type)
Example :
Incrementing pointer variable on 64 bit OS
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 3;
int *j;//pointer to int
j = &i;//stores the address of i variable
printf("Address of i variable is %u \n", j);
j = j+1; // incrementing pointer by 1(4 bytes)
printf("After increment: Address of i variable is %u \n",j);
}
Output :
Address of i variable is 65524 After increment: Address of i variable is 65528 Explanation : For 32 bit int variable, it will increment to 2 byte. For 64 bit int variable, it will increment to 4 byte.
Decrement :
The formula of decrementing pointer is given below :
new_address= current_address - i * size_of(data type)
Example :
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 3;
int *j;//pointer to int
j = &i;//stores the address of i variable
printf("Address of i variable is %u \n",j);
j = j - 1; //decrementing pointer by 1(4 bytes)
printf("After decrement: Address of i variable is %u \n",j);
}
Output :
Address of i variable is 65524 After decrement: Address of i variable is 65520
Pointer Addition
We can add a value to the pointer variable.
The formula of adding value to pointer is given below :
new_address= current_address + (value * size_of(data type))
Example :
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 3;
int *j;//pointer to int
j = &i;//stores the address of i variable
printf("Address of i variable is %u \n", j);
j = j+3; // incrementing pointer by 4*3=12 bytes
printf("After increment: Address of i variable is %u \n",j);
}
Output :
Address of i variable is 65524 After increment: Address of i variable is 65536
Explanation :
For 32 bit int variable, it will add 2 * number.
For 64 bit int variable, it will add 4 * number.
For 64 bit int variable, it will add 4 * number.
Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable.
The formula of subtracting value from pointer variable is given below :
new_address= current_address - (value * size_of(data type))
Example :
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 3;
int *j;//pointer to int
j = &i;//stores the address of i variable
printf("Address of i variable is %u \n", j);
j = j - 3; // decrementing pointer by 4*3=12 bytes
printf("After increment: Address of i variable is %u \n",j);
}
Output :
Address of i variable is 65524 After increment: Address of i variable is 65512
No comments:
Post a Comment