C pointer arithmetic

后端 未结 5 1756
夕颜
夕颜 2020-12-05 11:32

Given this code:

int *p, *q;

p = (int *) 1000;
q = (int *) 2000;

What is q - p and how?

5条回答
  •  一生所求
    2020-12-05 12:16

    q - p is 250.

    2000 - 1000 = 1000
    1000 / sizeof(int) = 250
    

    pointer arithmetic, assuming sizeof(int) is 4.


    Edit: OK, to clarify. In C when two pointers are of the same type then the difference between them is defined the number of things of the pointed-to type between them. For example,

    struct foo { int ar[1000]; } big[10];
    char small[10];
    
    struct foo *fs, *fe;
    char *ss, *se;
    
    fs = &big[0]; fe = &big[9];
    ss = &small[0]; se = &small[9];
    
    fe - fs == se - ss;
    

    That is, the difference between the two pointers in this case is the number of array elements between them. In this case it is 0, 1, ... 8 or 9 elements.

提交回复
热议问题