Pointer Addition in C

C 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 + (number * size_of(data type)) 

#include <stdio.h>          
void main(){          
int number=50;      
int *p;//pointer to int    
p=&number;//stores the address of number variable      
          
printf("Address of p variable is %u \n",p);      
p=p+3;   //adding 3 to pointer variable  
printf("After adding 3: Address of p variable is %u \n",p);      
}
Output
Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312


  • As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. 
  • Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.
https://mskuthar.blogspot.com/2015/02/pointer-addition.html
Pointer Addition

#include <stdio.h>
int main()
{
   int first, second, *p, *q, sum;

   printf("Enter two integers to add\n");
   scanf("%d%d", &first, &second);

   p = &first;
   q = &second;

   sum = *p + *q;

   printf("Sum of the numbers = %d\n", sum);

   return 0;
}
Output
Enter two integers to add
5
6
Sum of the numbers =11

C program to add numbers using call by reference
#include <stdio.h>
long add(long *, long *);

int main()
{
   long first, second, *p, *q, sum;

   printf("Input two integers to add\n");
   scanf("%ld%ld", &first, &second);

   sum = add(&first, &second);

   printf("(%ld) + (%ld) = (%ld)\n", first, second, sum);

   return 0;
}

long add(long *x, long *y) {
   long sum;
   
   sum = *x + *y;
   
   return sum;
}


Post a Comment

Previous Post Next Post