pointer arithmetic in c

pointer arithmetic in c

There are all types of operations not possible with pointers, only some valid operations are valid with pointer, There are some operations are used with pointer
(1) Increment
(2) Decrement
(3) Addition
(4) Subtraction
(5) Comparison

OR

(1) Addition of an integer to a pointer and increment operation
(2) subtraction of an integer from a pointer and its decrement operation
(3) subtraction of a pointer from another pointer of same type

Increment pointer in C

If we increment a pointer by one, the pointer will pointing to the immediate next location. This is the different from the general arithmetic so the value of the pointer get increased by the same size of the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on pointer which will pointing to every element of array, perform some operation on that, and update.

The Formula for increment pointer

new_address= current_address + i * size_of(data type)

Here in the formula i is the number by which the pointer get increased.

For 64-bit platform int variable, it incremented by 4 bytes

For 32-bit platform int variable, it incremented by 2 bytes.

data_type **ptr;

In this example here variable ptr is a pointer to pointer variable that can store the address of pointer variable of data_type. Here the double esterisk used in the declaration indicated or inform to the compiler that pointer to pointer variable is declared. so now take the example with it

int a=34;
int *ptr=&a;
int **pptr=&ptr;

In this example first declare variable a and in the second statement pointer variable is declare of type int ptr and stored the address of variable a to the ptr pointer variable, In the last statement pointer to pointer variable is declare pptr which store address of pointer variable

arithmetic pointer in c

/* dereferencing pointer variable */
#include<stdio.h>
int
main()
{
int a=56;
float b=8.5;
int *ptr1=&a;
float *ptr2=&b;
printf("value of ptr1= Address of a=%p\n",ptr1);
printf("value of ptr2= Address of b=%p\n",ptr2);
printf("Value of a=%d, %d, %d \n",a,*ptr1,*(&a));
printf("Value of b=%d, %d, %d \n",b,*ptr2,*(&b));
return 0;
}

Decrementing Pointer in C

Like same as above example of increment, we can decrement a pointer variable. when we decrement a pointer, it start pointing to the previous location.

The formula of decrementing the pointer is given below:

new_address= current_address – i * size_of(data type)

/* dereferencing pointer variable */
#include<stdio.h>
void main()
{
int num=40;
int *p;//pointer to int
p=#//here stores the address of num variable
printf("Address of the p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of the p variable is %u \n",p); // P will now point to the immediate previous location
}

Address of the p variable is 2986262228
After decrement: Address of the p variable is 2986262224