adress problem

int ar[]={3,2,4};

printf("%d",&ar[1]-&ar[0]);


it gave 1 , but I was expecting 4.Because the distance between 2 integers is 4 byte why it printed 1?
You basically wrote this: ar+1-ar.
There's two possibilities here:
1. The compiler rearranged the operations.
ar-ar+1
ar-ar+1
1
2.
The result is given in pointer arithmetic. Always remember that if int *a, and *a==1, *(a+1) won't give you a value between two ints.

EDIT: It's option 2.
Last edited on
Unfortunately I dont understand. Basicly I am subtacting 2 consecutive addresses , and I know the distance between them is 4 .....

in oder to be more clear , I add some new parts in my code..

when I use sizeof function it gives me 4 that I want..
what is the diffrerance between

printf("%d\n",&ar[1]-&ar[0]);
printf("%d\n",sizeof(&ar[1]-&ar[0]));



int ar[]={3,2,4};

printf("%p\n",&ar[1]);
printf("%p\n",&ar[0]);

printf("%d\n",&ar[1]-&ar[0]);
printf("%d\n",sizeof(&ar[1]-&ar[0]));

Last edited on
Yes, the distance between them is 4 bytes. ints, however, are (in this case) dwords. The distance between them is 1 dword.
If you want to get the distance in bytes, you need to cast the pointers to void * before doing the subtraction.
Last edited on
Well I would have thought that you would have gotten -1.

1
2
3
int ar[]={3,2,4};

printf("%d",&ar[1]-&ar[0]);


This sets up an array like this...
1
2
3
4
____________
|0|____3____|
|1|____2____|
|2|____4____|


Because when you set up arrays then they are set up as 0, 1, 2, 3, 4, 5 and not 1, 2, 3, 4, 5. So if you call &ar[0] then you are calling the pointer to 3. Am I wrong here?
You are right. You're getting the pointer to 3. Not 3 itself.
"If you want to get the distance in bytes, you need to cast the pointers to void * before doing the subtraction."

could you add this to the code. Because ı dont know what to do..
((void *)(ar+1))-((void *)ar)
Last edited on
Topic archived. No new replies allowed.