C Program to Apply Subtraction on Pointer

24 May 2023 Balmiki Mandal 0 C Programming

Implementing Pointer Subtraction in C: A Practical Example

A pointer is a variable that stores the address of another variable. In C, we can subtract one pointer from another pointer to get the difference between their addresses. This can be useful for a variety of tasks, such as finding the length of an array or calculating the difference between two elements in an array.

Program: C program subtracts two pointers to find the length of an array:

#include<stdio.h>

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int *ptr1 = arr;
  int *ptr2 = &arr[4];

  int len = ptr2 - ptr1;

  printf("The length of the array is %d\n", len);

  return 0;
}
output:
The length of the array is: 5

As you can see, the difference between the addresses of the two pointers is 5, which is the length of the array.

 

We can also use pointer subtraction to calculate the difference between two elements in an array. For example, the following C program calculates the difference between the first and last elements in an array:

#include<stdio.h>
int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int *ptr1 = arr;
  int *ptr2 = &arr[4];

  int diff = *ptr2 - *ptr1;

  printf("The difference between the first and last elements in the array is %d\n", diff);

  return 0;
}

This program will print the following output:

The difference between the first and last elements in the array is 4
As you can see, the difference between the values pointed to by the two pointers is 4, which is the difference between the first and last elements in the array.

Pointer subtraction is a powerful tool that can be used for a variety of tasks in C. By understanding how it works, you can write more efficient and effective code.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.