Learning coding means GreatToCode Be more than a Coder ! Greattocode , Join GreatToCode Community,1000+ Students Trusted On Us .If You want to learn coding, Then GreatToCode Help You.No matter what It Takes !


CODE YOUR WAY TO A MORE FULFILLING And HIGHER PAYING CAREER IN TECH, START CODING FOR FREE Camp With GreatToCode - Join the Thousands learning to code with GreatToCode
Interactive online coding classes for at-home learning with GreatToCode . Try ₹Free Per Month Coding Classes With The Top Teachers . Pointer Arithmetics in C with Examples

Pointer Arithmetics in C with Examples


 

Pointer Arithmetics in C with Examples

________________________________________________________________________


Pointers variables are also known as address data types because they are used to store the address of another variable. The address is the memory location that is assigned to the variable. It doesn’t store any value. 

Hence, there are only a few operations that are allowed to perform on Pointers in C language. The operations are slightly different from the ones that we generally use for mathematical calculations. The operations are: 

  1. Increment/Decrement of a Pointer
  2. Addition of integer to a pointer
  3. Subtraction of integer to a pointer
  4. Subtracting two pointers of the same type
  5. Comparison of pointers of the same type.

Increment/Decrement of a Pointer

Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. 

For Example: 
If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002. While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer. 

For Example: 
If an integer pointer that stores address 1000 is decremented, then it will decrement by 2(size of an int) and the new address it will points to 998. While if a float type pointer is decremented then it will decrement by 4(size of a float) and the new address will be 996.

Below is the program to illustrate pointer increment/decrement: 

// C program to illustrate
// pointer increment/decrement
 
#include <stdio.h>
 
// Driver Code
int main()
{
    // Integer variable
    int N = 4;
 
    // Pointer to an integer
    int *ptr1, *ptr2;
 
    // Pointer stores
    // the address of N
    ptr1 = &N;
    ptr2 = &N;
 
    printf("Pointer ptr1 "
           "before Increment: ");
    printf("%p \n", ptr1);
 
    // Incrementing pointer ptr1;
    ptr1++;
 
    printf("Pointer ptr1 after"
           " Increment: ");
    printf("%p \n\n", ptr1);
 
    printf("Pointer ptr1 before"
           " Decrement: ");
    printf("%p \n", ptr1);
 
    // Decrementing pointer ptr1;
    ptr1--;
 
    printf("Pointer ptr1 after"
           " Decrement: ");
    printf("%p \n\n", ptr1);
 
    return 0;
}
Output
Pointer ptr1 before Increment: 0x7ffefa9c5704 
Pointer ptr1 after Increment: 0x7ffefa9c5708 

Pointer ptr1 before Decrement: 0x7ffefa9c5708 
Pointer ptr1 after Decrement: 0x7ffefa9c5704 

Addition

When a pointer is added with a value, the value is first multiplied by the size of data type and then added to the pointer.

// C program to illustrate pointer Addition
#include <stdio.h>
 
// Driver Code
int main()
{
    // Integer variable
    int N = 4;
 
    // Pointer to an integer
    int *ptr1, *ptr2;
 
    // Pointer stores the address of N
    ptr1 = &N;
    ptr2 = &N;
 
    printf("Pointer ptr2 before Addition: ");
    printf("%p \n", ptr2);
 
    // Addition of 3 to ptr2
    ptr2 = ptr2 + 3;
    printf("Pointer ptr2 after Addition: ");
    printf("%p \n", ptr2);
 
    return 0;
}
Output
Pointer ptr2 before Addition: 0x7fffc22348a4 
Pointer ptr2 after Addition: 0x7fffc22348b0 

Subtraction

When a pointer is subtracted with a value, the value is first multiplied by the size of the data type and then subtracted from the pointer.

Below is the program to illustrate pointer Subtraction:

// C program to illustrate pointer Subtraction
#include <stdio.h>
 
// Driver Code
int main()
{
    // Integer variable
    int N = 4;
 
    // Pointer to an integer
    int *ptr1, *ptr2;
 
    // Pointer stores the address of N
    ptr1 = &N;
    ptr2 = &N;
 
    printf("Pointer ptr2 before Subtraction: ");
    printf("%p \n", ptr2);
 
    // Subtraction of 3 to ptr2
    ptr2 = ptr2 - 3;
    printf("Pointer ptr2 after Subtraction: ");
    printf("%p \n", ptr2);
 
    return 0;
}
Output
Pointer ptr2 before Subtraction: 0x7ffcbed44ee4 
Pointer ptr2 after Subtraction: 0x7ffcbed44ed8 

Subtraction of Two Pointers

The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. 

For Example: 
Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are subtracted. The difference between address is 16 bytes. Since the size of int is 2 bytes, therefore the increment between ptr1 and ptr2 is given by (16/2) = 8.

Below is the implementation to illustrate the Subtraction of Two Pointers:

// C program to illustrate Subtraction
// of two pointers
#include <stdio.h>
 
// Driver Code
int main()
{
    int x;
 
    // Integer variable
    int N = 4;
 
    // Pointer to an integer
    int *ptr1, *ptr2;
 
    // Pointer stores the address of N
    ptr1 = &N;
    ptr2 = &N;
 
    // Incrementing ptr2 by 3
    ptr2 = ptr2 + 3;
 
    // Subtraction of ptr2 and ptr1
    x = ptr2 - ptr1;
 
    // Print x to get the Increment
    // between ptr1 and ptr2
    printf("Subtraction of ptr1 "
           "& ptr2 is %d\n",
           x);
 
    return 0;
}
Output
Subtraction of ptr1 & ptr2 is 3

Pointer Arithmetic on Arrays: 
Pointers contain addresses. Adding two addresses makes no sense because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between the two addresses. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For Example: if an array named arr then arr and &arr[0] can be used to reference array as a pointer.

Below is the program to illustrate the Pointer Arithmetic on arrays:

Program 1: 

// C program to illustrate the array
// traversal using pointers
#include <stdio.h>
 
// Driver Code
int main()
{
 
    int N = 5;
 
    // An array
    int arr[] = { 1, 2, 3, 4, 5 };
 
    // Declare pointer variable
    int* ptr;
 
    // Point the pointer to first
    // element in array arr[]
    ptr = arr;
 
    // Traverse array using ptr
    for (int i = 0; i < N; i++) {
 
        // Print element at which
        // ptr points
        printf("%d ", ptr[0]);
        ptr++;
    }
}
Output
1 2 3 4 5 

Program 2: 

// C program to illustrate the array
// traversal using pointers in 2D array
#include <stdio.h>
 
// Function to traverse 2D array
// using pointers
void traverseArr(int* arr,
                 int N, int M)
{
 
    int i, j;
 
    // Traverse rows of 2D matrix
    for (i = 0; i < N; i++) {
 
        // Traverse columns of 2D matrix
        for (j = 0; j < M; j++) {
 
            // Print the element
            printf("%d ", *((arr + i * M) + j));
        }
        printf("\n");
    }
}
 
// Driver Code
int main()
{
 
    int N = 3, M = 2;
 
    // A 2D array
    int arr[][2] = { { 1, 2 },
                     { 3, 4 },
                     { 5, 6 } };
 
    // Function Call
    traverseArr((int*)arr, N, M);
    return 0;
}
Output
1 2 
3 4 
5 6 

Comparison of pointers of the same type:

We can compare the two pointers by using the comparison operators in C. We can implement this by using all operators in C >, >=, <, <=, ==, !=.  It returns true for the valid condition and returns false for the unsatisfied condition. 

Step 1 : Initialize the integer values and point these integer values to the pointer.

Step 2 : Now, check the condition by using comparison or relational operators on pointer variables.

Step 3 : Display the output.

#include <stdio.h>
 
int main() {
 
    // code
    int num1=5,num2=6,num3=5; //integer input
    int *p1=&num1;// addressing the integer input to pointer
    int *p2=&num2;
    int *p3=&num3;
    //comparing the pointer variables.
   if(*p1<*p2)
   {
       printf("\n%d less than %d",*p1,*p2);
   }
   if(*p2>*p1)
   {
     printf("\n%d greater than %d",*p2,*p1);
   }
   if(*p3==*p1)
   {
      printf("\nBoth the values are equal");
   }
   if(*p3!=*p2)
   {
      printf("\nBoth the values are not equal");
   }
   
 
    return 0;
}
Output
5 less than 6
6 greater than 5
Both the values are equal
Both the values are not equal

Comparison operators on Pointers using array :

In the below approach, it results the count of odd numbers and even numbers in an array. We are going to implement this by using pointer.

Step 1 :First, declare the length of an array and array elements. 

Step 2 :Declare the pointer variable and point it to the first element of an array. 

Step 3:Initialize the count_even and count_odd. Iterate the for loop and check the conditions for number of odd elements and even elements in an array,

Step 4: Increment the pointer location ptr++ to the next element in an array for further iteration.

Step 5 : Print the result.

#include <stdio.h>
 
int main()
{
    int n = 10; // length of an array
 
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int* ptr; // Declaration of pointer variable
 
    ptr = arr; // Pointer points the first (0th index)
               // element in an array
    int count_even = 0;
    int count_odd = 0;
 
    for (int i = 0; i < n; i++) {
 
        if (*ptr % 2 == 0) {
            count_even++;
        }
        if (*ptr % 2 != 0) {
            count_odd++;
        }
        ptr++; // Pointing to the next element in an array
    }
    printf("\n No of even elements in an array is : %d",
           count_even);
    printf("\n No of odd elements in an array is : %d",
           count_odd);
}
Output
 No of even elements in an array is : 5
 No of odd elements in an array is : 5



Indirection (*)This operator is used to get the value from the pointed address.
Reference operator (&)This operator is used to get the address of the variable or pointer.
Assignment (=)You can assign the value to the pointer or value to the address which is pointed by the pointer.
Addition (+)You can add integer value to the pointer to point the different memory locations.
Subtraction (-)You can subtract the integer value from the pointer to point the different memory locations.
comparison (==, !=, <, >, <=, and >=)This operation is valid only between two pointers that point to the same array.
Incrementing (++)You can use increment operators (pre and post) with the pointer.
Decrementing (–)You can use decrement operators (pre and post) with the pointer.

 

Note: When we increment or decrement the pointer then pointer increase or decrease a block of memory (block of memory depends on pointer data type).

 

How does pointer arithmetic work

When we increment or decrement the pointer then pointer point to the next or previous memory location. Generally, people make mistakes, when they calculate the next pointing address of the pointer.

Here is the technique to calculate the next pointing address of a pointer when applying arithmetic operation on it. To understand this technique let us consider ptr is a pointer has data type “T” and “i” is the pointer offset.

addr( ptr + i ) = addr( ptr ) + ( sizeof( T ) * i );
addr( ptr - i ) = addr( ptr ) - ( sizeof( T ) * i );

 

Pointer Arithmetic on Character Pointer:

If we increment the character pointer by 1 then it will point to the address which will be just 1 byte more to the current pointing address.  Let us see an example where pcData is a character pointer and we performing an arithmetic operation on it.

char *pcData =NULL;

 

When we increment the pcData then it points to the next character location without impacting the stored data. The size of the character is 1 byte that’s why pointer moves only 1 byte of memory. .

pcData++;

 

So let us see how is the above technique work here to calculate the next pointing address.

You can see that the next pointing address only 1 byte more to the current pointing address because the size of the character is 1 byte.

When you perform arithmetic subtraction on pointer then you have to use the second technique which describes in the beginning. The basic concept will be the same difference is only that here you need to subtract the calculated offset from the pointing address.

 

Similar to that If we add 2 to the pcData (character pointer ) then pcData will point to the next 2 bytes of the current pointing position.

char *pcData = NULL;
pcData = pcData + 2;

 

 

 

 

 

 

 

In this table, we have summarized the arithmetic operation on the character pointer. So pcData is a character pointer and suppose initially it points to an address “3000”.

Pointer Expression

How it is evaluated ?

pcData + 1

pcData = pcData + 1 => 3000 + 1*1 => 3001

pcData++ or ++pcData

pcData => pcData + 1 => 3000 + 1*1 => 3001

pcData = pcData + 5

pcData => pcData + 5 => 3000 + 5*1 => 3005

pcData = pcData – 2

pcData => pcData – 2 => 3000 – 2*1 => 2998

pcData– or –pcData

pcData => pcData – 1 => 3000 – 1*1 => 2999

 

Pointer Arithmetic on Float Pointer:

Like the character pointer, when we increment the float pointer then it points to the next float location without impacting the stored data. Let us see an example where pfData is a float pointer and we performing an arithmetic operation on it.

float *pfData = NULL;

 

When we increment the pfData then it points to the next float location without impacting the stored data. Here we are assuming float size is 4 bytes. So when we increment the float pointer by 1 then it will point to the address which will be just 4 bytes more to the current pointing address.

pfData++;

 

So let us see how is the above technique work here to calculate the next pointing address for the float pointer.

addr( pfData + 1 ) = addr( pfData ) + [ sizeof( float) * 1 ];
addr( pfData + 1 ) = addr( pfData ) + [ 4 * 1 ];
addr( pfData + 1 ) = addr( pfData ) + 4;

 


Post a Comment

0 Comments

•Give The opportunity to your child with GreatToCode Kid's • Online Coding Classes for Your Kid • Introduce Your kid To the world's of coding
•Fuel You Career with our 100+ Hiring Partners, Advance Your Career in Tech with GreatToCode. •Join The Largest Tech and coding Community and Fast Forward Your career with GreatToCode. •10000+ Learner's+ 90 % placement Guarantee. • Learning Coding is Better with the GreatToCode community .
•Greattocode Kid's •GreatToCode Career •GreatToCode Interview •GreatToCode Professional •GreatToCode for schools •GreatToCode For colleges •GreatToCods For Businesses.
Are you ready to join the millions of people learning to code? GreatToCode Pass is your one-stop-shop to get access to 1000+ courses, top-notch support, and successful job placement. What are you waiting for? Sign up now and get your future in motion with GreatToCode Pass.