This was the code that was given in a previous forum
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
static int a[]={0,1,2,3,4};
static int *p[]={a,a+2,a+1,a+4,a+3};
int **ptr;
ptr=p;
**++ptr;
cout<<**ptr<<" "<<ptr-p<<" "<<*ptr-a;
}
The answer was this
a[0] = 0 // This is what happened when you set a
a[1] = 1
a[2] = 2
a[3] = 3
a[4] = 4
p[0] = a[0] = 0 // this is what happened when you set p
p[1] = a[2] = 2
p[2] = a[1] = 1
p[3] = a[4] = 4
p[4] = a[3] = 3
**ptr = p[0] = a[0] = 0 // this is what happened when you set ptr = p
**ptr = p[1] = a[2] - 2 // this is what happened after ++ptr
cout << **ptr = p[1] = a[2] = 2
<< ptr - p = p+1 - p = 1
<< *ptr - a = *(p+1) - a = a+2 - a = 2
----------------
I'm confused about this line ptr - p = p+1 - p = 1
ptr = p+1 = p[1]= a[1]=2 I understand that, but if the answer is 1 than 2-1 =1
how do you get 1 from p what does p equal, I thought p = p[0]=a[0]=0
**ptr = p[0] = a[0] = 0 // this is what happened when you set ptr = p
**ptr = p[1] = a[2] - 2 // this is what happened after ++ptr
are incorrect. Must be
**ptr = *p[0] = a[0] = 0 // this is what happened when you set ptr = p
**ptr = *p[1] = a[2] - 2 // this is what happened after ++ptr
As for expression
ptr-p
then initially ptr was equal to p
int **ptr;
ptr=p;
Then it was incremented
**++ptr;
It could be written simply as ++ptr; There is no need to dereference the pointer.
Record ++ptr is equivalent to ptr = ptr + 1. As ptr is equal to p then it can be rewriten as ptr = p + 1. So
ptr - p is equivalent to (p + 1) - p that equal to 1.
thanks, why does cout << ptr and cout << p give me an address but cout << ptr -p give me a 1, because if I subtract the one address from the other I don't get a 1.
These are probably pretty stupid questions so I appreciate your help.
A pointer has associated with it the size of the type of object it points to.
So when we do for example ptr + 1 or ptr - p it is not simply adding or subtracting the value of the address. Rather it is taking into consideration the size of the data type.
A pointer to an int uses the size in bytes of an integer as the quantity to be added to or subtracted from the address each time.
Say we have an integer requiring 4 bytes (this may vary, try sizeof(int) for the actual value). Then adding 1 to a pointer to an int will increase the address by 4.
The pointer arithmetic deals with units of type. So for example
p + 1 means to increase p by one unit of the given type. if p has type int * then p + 1 will point next object of type int relative to the object pointed by p.
If p and q are two pointers of the same type of an array then p - q (let assume that p is greater than q) will be equal to the number of objects that are placed starting from q and ending with p exclusively.