Why is the difference between the two addresses wrong? http://codepad.org/NGDqFWjJ
#include<stdio.h>
int main()
{
int i = 10, j = 20;
int *p = &i;
int *q = &j;
int c = p - q;
printf("%d\n", p);
printf("%d\n", q);
printf("%d", c);
return 0;
}
Output:
-1083846364
-1083846368
1
A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address.
You can't change the address of a pointer (or of any variable). Once you declare the variable, it's address is firmly set, once and forever. You can, however, change the value of a pointer, just as easily as you can change the value of an int: x = 10 or p = &t.
So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.
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.
First, pointer arithmetic isn't defined when performed on unrelated pointers.
Second, it makes sense. When subtracting pointers you get the number of elements between those addresses, not the number of bytes.
If you were to try that with
char *p1 = &i, *p2 = &j;
you would get a different result.
As a side note, use %p
when printing pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With