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.
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.
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);
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Why strcpy and strncpy are not safe to use?
- Why "&" is not used for strings in scanf() function?
- Why variable name does not start with numbers in C ?
- Why does sizeof(x++) not increment x in C?
- Why is the size of an empty class not zero in C++?
- Why C treats array parameters as pointers?
- Why copy constructor argument should be const in C++?
- Why is a[i] == i[a] in C/C++ arrays?
- Why is C considered faster than other languages ?
- Why strict aliasing is required in C ?
- Why are elementwise additions much faster in separate loops than in a combined loop?
- Why array index starts from zero ?
- Why learning C Programming is a must?
- Why to use fgets() over scanf() in C?
- Why do we need reference variables if we have pointers
- Change/add only one character and print '*' exactly 20 times
- How to make a C++ class whose objects can only be dynamically allocated?
- Print a long int in C using putchar() only
- Do not use sizeof for array parameters
- Write a C program that does not terminate when Ctrl+C is pressed
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.