Why only subtraction of addresses allowed and not division/addition/multiplication

Why Subtraction is allowed? Two addresses can be subtracted because the memory between the two addresses will be valid memory.
Let’s assume memory Ptr_1 and ptr_2 valid addresses. It is obvious that memory between these two addresses is valid.
Pointer ptr_1 is pointing to 0x1cb0010 memory location and ptr_2 is pointing to 0x1cb0030 memory location. If we subract ptr_1 from ptr_2, then the Memory region will lie in between these two location which is obviously a valid memory location.

// C program to demonstrate that pointer
// subtraction is allowed.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int* ptr_1 = (int*)malloc(sizeof(int));
    int* ptr_2 = (int*)malloc(sizeof(int));
    printf("ptr_1: %p  ptr_2: %p\n", ptr_1, ptr_2);
    printf("Difference: %lu", ptr_2 - ptr_1);
    free(ptr_1);
    free(ptr_2);
    return 0;
}
Output:
ptr_1: 0x1cb0010 ptr_2: 0x1cb0030
Difference: 8

Why addition, Multiplication, division or modulus is not allowed??
If we perform addition, multiplication, division or modulus on ptr_1 and ptr_2, then the resultant address may or may not be a valid address. That can be out of range or invalid address. This is the reason compiler doesn’t allow these operations on valid addresses.

// C program to demonstrate addition / division 
// / multiplication not allowed on pointers.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int* ptr_1 = (int*)malloc(sizeof(int));
    int* ptr_2 = (int*)malloc(sizeof(int));
    printf("addition:%lu multipicaion:%lu division:%lu\n",
           ptr_2 + ptr_1, ptr_2 * ptr_1, ptr_2 / ptr_1);
    free(ptr_1);
    free(ptr_2);
    return 0;
}
Output: prog.c: In function 'main':
prog.c:8:60: error: invalid operands to 
binary + (have 'int *' and 'int *')
printf("addition:%lu multipicaion:%lu 
division:%lu\n", ptr_2+ptr_1, ptr_2*ptr_1,
ptr_2/ptr_1);


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Practice Tags :
Article Tags :
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 2 vote(s)






User Actions