adress problem
| ozgungor (6) | |||
| 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? | |||
| helios (1520) | |||
| You basically wrote this: ar+1-ar. 1. The compiler rearranged the operations. ar-ar+1 ar-ar+1 1 2. EDIT: It's option 2. | |||
| ozgungor (6) | |||
| 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])); | |||
| helios (1520) | |||
| 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. | |||
| kryptonite (36) | |||||
Well I would have thought that you would have gotten -1.
This sets up an array like this...
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? | |||||
| helios (1520) | |||
| You are right. You're getting the pointer to 3. Not 3 itself. | |||
| ozgungor (6) | |||
| "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.. | |||
| helios (1520) | |||
| ((void *)(ar+1))-((void *)ar) | |||
This topic is archived - New replies not allowed.
