Pointer Arithmetics In C With Examples

Pointer Arithmetics In C With Examples

Pointer arithmetic is a set of operations that can be performed on pointers, which are variables that store memory addresses. These operations are different from traditional mathematical calculations because they are performed in the context of memory addresses and the data types they point to.

Some of the operations are done by the pointer in C language. Some of 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

1. Increment/Decrement of a Pointer

Increment: When you increment a pointer in C, it moves to the next memory location based on the size of the data it points to. For example, if you have an integer pointer and you increment it, it will jump to the next integer-sized space in memory (usually 4 bytes). The same applies to float pointers; they move by the size of a float (typically 4 bytes) when incremented. This way, pointers stay aligned with the data they point to.

Decrement: When a pointer is decremented in C, it moves backward by an amount equal to the size of the data type it is pointing to. Your examples illustrate this effectively:

  • If you have an integer pointer and you decrement it, it moves back by 4 bytes (assuming a standard 4-byte integer on most systems).
  • If you have a float pointer and you decrement it, it also moves back by 4 bytes (assuming a standard 4-byte float).

This ensures that when you decrement a pointer, it correctly points to the previous element of the data type it references, no matter the specific data type. Understanding this behavior is crucial when working with pointers and pointer arithmetic to manage memory effectively.

Example of Pointer Increment and Decrement

#include <stdio.h>
// pointer increment and decrement
//pointers are incremented and decremented by the size of the data type they point to 
int main()
{
    int a = 22;
    int *p = &a;
    printf("p = %u\n", p); // p = 6422288
    p++;
    printf("p++ = %u\n", p); //p++ = 6422292    +4   // 4 bytes
    p--;
    printf("p-- = %u\n", p); //p-- = 6422288     -4   // restored to original value
 
    float b = 22.22;
    float *q = &b;
    printf("q = %u\n", q);  //q = 6422284
    q++;
    printf("q++ = %u\n", q); //q++ = 6422288      +4   // 4 bytes
    q--;
    printf("q-- = %u\n", q); //q-- = 6422284       -4  // restored to original value
 
    char c = 'a';
    char *r = &c;
    printf("r = %u\n", r);   //r = 6422283
    r++;
printf("r++ = %u\n", r);   //r++ = 6422284     +1   // 1 byte
    r--;
    printf("r-- = %u\n", r);   //r-- = 6422283     -1  // restored to original value
 
    return 0;
}

Output

p = 1441900792
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791

2. Addition of Integer to Pointer

When you add an integer to a pointer, the integer value is first multiplied by the size of the data type to which the pointer points, and then the result is added to the pointer’s address.

In your example:

  • You have an integer pointer storing the address 1000.
  • When you add the integer 5 to it with the expression ptr = ptr + 5, the final address stored in ptr will be calculated as follows: 1000 + sizeof(int) * 5, which is equal to 1020.

This behavior ensures that when you perform pointer arithmetic with an integer value, the pointer correctly advances by the appropriate number of bytes based on the data type’s size. It’s an essential concept for navigating and manipulating data structures in memory.

Example of Addition of Integer to 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: 0x7ffca373da9c 
Pointer ptr2 after Addition: 0x7ffca373daa

3. Subtraction  of Integer to Pointer

When you subtract an integer from a pointer, the integer value is first multiplied by the size of the data type to which the pointer points, and then the result is subtracted from the pointer’s address.

In your example:

  • You have an integer pointer storing the address 1000.
  • When you subtract the integer 5 from it with the expression ptr = ptr - 5, the final address stored in ptr will be calculated as follows: 1000 - sizeof(int) * 5, which is equal to 980.

This behavior ensures that when you perform pointer arithmetic with a subtracted integer value, the pointer correctly moves backward by the appropriate number of bytes based on the data type’s size. This is an important concept when navigating and manipulating data structures in memory.

Example


// 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: 0x7ffd718ffebc 
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0

4. Subtraction of Two Pointers

When you subtract two pointers that point to the same data type, the result is calculated by finding the difference between their addresses and then dividing by the size of the data type to determine how many elements (not bytes) separate the two pointers.

In your example:

  • You have two integer pointers, ptr1 with an address of 1000 and ptr2 with an address of 1004.
  • When you subtract these two pointers (ptr2 - ptr1), you get a result of 4 bytes, which is the difference in addresses.
  • Since the size of an integer is 4 bytes, you divide the address difference by the size of the data type: (4 / 4), which equals 1. This means there is an increment of 1 integer-sized element between ptr1 and ptr2.

This operation is useful for calculating the distance or offset between two pointers and is valuable for various pointer-related tasks, such as working with arrays and data structures.

Example

// C program to illustrate Subtraction
// of two pointers
#include <stdio.h>
 
// Driver Code
int main()
{
    int x = 6; // Integer variable declaration
    int N = 4;
 
    // Pointer declaration
    int *ptr1, *ptr2;
 
    ptr1 = &N; // stores address of N
    ptr2 = &x; // stores address of x
 
    printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);
    // %p gives an hexa-decimal value,
    // We convert it into an unsigned int value by using %u
// Subtraction of ptr2 and ptr1
    x = ptr1 - ptr2;
 
    // Print x to get the Increment
    // between ptr1 and ptr2
    printf("Subtraction of ptr1 "
           "& ptr2 is %d\n",
           x);
 
    return 0;
}
 

Output

ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1

5. Comparison of Pointers

You can compare pointers using operators like >, >=, <, <=, ==, and !=. These operators return true for valid conditions and false for unsatisfied conditions.

Here are the steps for comparing pointers in C:

Step 1: Initialize integer values and point these integer values to the pointers. Step 2: Use comparison or relational operators to check conditions on the pointer variables. Step 3: Display the output, which will indicate whether the specified conditions between the pointers are met.

Pointer comparison is useful for tasks such as checking whether one pointer points to an element before or after another pointer in an array or to validate if two pointers point to the same memory location.

Example


// C Program to illustrare pointer comparision
#include <stdio.h>
 
int main()
{
    // declaring array
    int arr[5];
 
    // declaring pointer to array name
    int* ptr1 = &arr;
    // declaring pointer to first element
    int* ptr2 = &arr[0];
 
    if (ptr1 == ptr2) {
        printf("Pointer to Array Name and First Element "
               "are Equal.");
    }
    else {
        printf("Pointer to Array Name and First Element "
               "are not Equal.");
    }
 
    return 0;
}

Output

Pointer to Array Name and First Element are Equal.

Comparison to NULL

In C and many other programming languages, a pointer can be compared to or assigned a NULL value regardless of its data type. A NULL pointer is a special value that indicates that the pointer doesn’t point to any valid memory location. It’s commonly used in error handling and to check whether a pointer is valid before attempting to access the memory it points to.


// C Program to demonstrate the pointer comparison with NULL
// value
#include <stdio.h>
 
int main()
{
 
    int* ptr = NULL;
 
    if (ptr == NULL) {
        printf("The pointer is NULL");
    }
    else {
        printf("The pointer is not NULL");
    }
    return 0;
}

Output

The pointer is NULL

Comparison operators on Pointers using an array

Step 1: Declare the length of the array and initialize the array elements.

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

Step 3: Initialize counters for even and odd numbers. Use a loop to iterate through the array and check each element for even or odd.

Step 4: Increment the pointer (move to the next element) for further iteration.

Step 5: Print the results.

Example

// Pointer Comparision in Array
#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("No of even elements in an array is : %d",
           count_even);
    printf("\nNo 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

Pointer Arithmetic on Arrays

Pointers in C and C++ contain memory addresses, and it doesn’t make sense to directly add two addresses together. However, subtracting two addresses, as you mentioned, allows you to compute the offset (in elements, not bytes) between those two addresses, which can be useful for various purposes, such as determining the difference between two array elements.

Regarding arrays and pointers:

  • An array name in C and C++ acts like a pointer to the first element of the array. You can use the array name itself (e.g., arr) or the address of the first element (e.g., &arr[0]) to reference the array as a pointer.

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

FAQ- Pointer Arithmetics In C With Examples

Q1. What is an example of a pointer arithmetic?

Ans. When you add an integer to a pointer in C, the pointer moves forward in memory based on the size of the data it points to. For example, if the pointer is pointing to an integer (typically 4 bytes in a 64-bit system) and you add +2, it will move 8 bytes ahead. This ensures that the pointer points to the next integer in the sequence. This concept helps you work with arrays and data structures effectively.

Q2. What is pointer and pointer arithmetic in C language?

Ans.In C, pointer arithmetic comprises a limited set of operations that work with memory addresses, not values. These operations include incrementing, decrementing, adding integers, subtracting integers, and comparing pointers. They are crucial for tasks like managing arrays and memory allocation.

Q3. Can we add two pointers in C?

Ans. Adding two-pointers is considered to be illegal. Whereas, we can add pointer and integer addition.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment