Pointer Addition & Subtraction in C
Notes:
Pointer Addition & Subtraction Operations in C Programming Language:
2. Addition and subtraction operations: pointer arithmetic in c
- To navigate from one memory location to another memory location of the same type directly; an integer value can be added to or subtracted from a pointer variable.
Note: the amount of value added to or subtracted from a pointer variable depends upon the size of its type
i.e.
pointerVariable + integerValue;
// expanded to pointerVariable + (integerValue * size of the its type)
pointerVariable - integerValue;
// expanded to pointerVariable - (integerValue * size of the its type)
Ex 1: int *iptr;
iptr = iptr + value;
// expanded to iptr = iptr + (value * size of the int type)
Ex:
iptr = iptr + 1;
// expanded to iptr = iptr + (1 * 4); === iptr = iptr + 4;
iptr points to Nextint type memory location ; which is 4 bytes away from the current memory location
Ex 2: short int *sptr;
sptr = sptr + value;
// expanded to sptr = sptr + (value * size of the short int type)
Ex:
sptr = sptr + 1;
// expanded to sptr = sptr + (1 * 2); === sptr = sptr + 2;
sptr points to Nextshort int type memory location ; which is 2 bytes away from the current memory location
Ex 3: char *cptr;
cptr = cptr + value;
// expanded to cptr = cptr + (value * size of the char type)
Ex:
cptr = cptr + 1;
// expanded to cptr = cptr + (1 * 1); === cptr = cptr + 1;
cptr points to Nextchar type memory location ; which is 1 byte away from the current memory location
Example Code:
#include <stdio.h>
int main()
{
int numbers[5] = {1,2,3,4,5};
int *iptr = &numbers[0]; // #20
printf("Value at iptr is pointing =%d\n",*iptr); // 1
iptr = iptr + 2; // iptr = #28
printf("Value at iptr is pointing =%d\n",*iptr); // 3
iptr = iptr + 2; // iptr = #36
printf("Value at iptr is pointing =%d\n",*iptr); // 5
iptr = iptr - 4; // iptr = #20
printf("Value at iptr is pointing =%d\n",*iptr); // 1
return 0;
}