Type Here to Get Search Results !

Pointer Arithmetic

Pointer Arithmetic

C pointer is an address, which is a numeric value. So, we can perform arithmetic operations on a pointer. There are four arithmetic operators that can be used on pointers: ++, --, + and –
Consider that ptr is an integer pointer which points to the address 2000. Let us perform the following arithmetic operation on the pointer:
prt++
The ptr will point to the location 2004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location.
This operation will move the pointer to the next memory location without impacting on the actual value at the memory location.
If ptr points to a character whose address is 2000, then the above operation will point to the location 2001 because the next character will be available at 2001

Incrementing a Pointer
We use a pointer instead of an array because the variable pointer can be incremented, but the array name cannot be increment because it is a constant pointer.

#include<stdio.h>
const int MAX=3;
int main()
{
/* Declaration and initializing an int array with 3 elements */
int var[] = {10,100,200};
int i, *ptr;
ptr=var; //Pointer now points to arrary i.e. first element
for(i=0; i<MAX; i++)
{
printf(“Address of var[%d]=%x\n”, i,ptr); //Address of the current element
printf(“Value of var[%d]=%d\n”,i, *ptr); //Content of the current element
ptr++; //move to the next location
}
return();
}

OUTPUT
Address of var[0] = fff0
Value of Var[0]=10
Address of var[1] = fff2
Value of var[1] = 100
Address of var[2] = fff4
Value of var[2] = 200

Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type.

#include<stdio.h>
const int MAX=3;
int main()
{
/* Declaration and initializing an int array with 3 elements */
int var[] = {10,100,200};
int i, *ptr;
ptr=&var[MAX-1]; //Pointer now points to array i.e. last element
for(i=MAX; i0;  i--)
{
printf(“Address of var[%d]=%x\n”, i,ptr); //Address of the current element
printf(“Value of var[%d]=%d\n”,i, *ptr); //Content of the current element
ptr--; //move to the previous location
}
return();
}

OUTPUT
Address of var[3] = fff4
Value of Var[3]=200
Address of var[2] = fff2
Value of var[2] = 100
Address of var[1] = fff0
Value of var[1] = 10


Top Post Ad

Below Post Ad