Can anyone help me with this. I thought pointer is a object that hold address of a variable. So when i minus a pointer to a pointer. it get this result.
int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = c - d; // = 3
int array[] = { 1, 2, 6, 4, 7, 8, 5, 3 };
int* f = &array[0];
int* g = &array[8];
int h = g - f; // = 8
You are right, a pointer holds address of an object in the memory. In C and C++ we can do pointer arithmetic which lets us subtract pointers from each other and more. Substracting pointers gives us the distance between the two addresses in the memory. The unit of the distance is determined by the pointer type. Meaning that subtracting two int*
s will give you how many int
s are your addresses apart. In your case variable e
will be the distance between where a
is stored in memory and where b
is stored in the memory. Running your code I got e=1
. Which I expect because a
and b
are defined right after each other so its expected that they will occupy two adjacent spaces on the stack but I guess its something that the compiler decides.
for arrays On the other hand, by definition all the elements are stored one after the other therefore the distance between the first and eighth element of any array is always 8
. Also take a look at the code below:
int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = d - c; // e=1
//the unit of measurement for pointer subtraction is the type of the pointer
//therefore although first byte of b is stored 4 bytes (sizeof(int)) after the
//first byte of a, we get '1' as the distance. but we cast the pointer to another type
//say char, we get distance based on that type
int f= (char*)d-(char*)c;//f=4 or e*4 since sizeof(int)=4*sizeof(char) (on this particular environment)