简体   繁体   中英

C pointer arithmetic while subtracting

int a[ ] ={1,3,5,7,9,11,13,15,17,19};
    int *pa = &a[4],*pb = &a[1];

What is the value of pa-pb ? Ans: 3, but how? Shouldn't it be 12 (like I printed pa and pb too, to double check, and got 12)?

Pointer arithmetic is very different from normal arithmetic. In pointer arithmetic a-1 , where a is pointer doesn't mean value of a subtracted with 1. it means go back by one unit of memory.

In your example, pa-pb doesn't mean value of pa-pb . one int variable requires 4 bytes so pa-pb means go back by three int's to reach pb from pa .

For int one unit of memory is 4 bytes, float 8 bytes, char 1 byte. NOTE: These value changes from system to system, its usually these value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM