When subtracting two pointers in C

后端 未结 5 1983
星月不相逢
星月不相逢 2021-01-07 12:18

I was playing with pointers in order to fully get the concept and then wanted to subtract two pointers expecting the distance between these two addresses or something, but a

5条回答
  •  渐次进展
    2021-01-07 12:47

    Your particular case is cause for undefined behavior since p and q point to unrelated objects.

    You can make sense of p-q only if p and q point to the same array/one past the last element of the same array.

    int array[10];
    int* p = &array[0];
    int* q = &array[5];
    
    int ptrdiff_t = q - p;  // Valid. diff1 is 5
    int ptrdiff_t = p - q;  // Valid. diff2 is -5
    

    q - p is 5 in this case since they point to elements of the array that are 5 elements apart.

    Put another way, p+5 is equal to q. If you start from p and step over 5 elements of the array, you will point to the same element of the array that q points to.


    As an aside, don't use the format specifier %d for printing pointers. Use %p. Use %td for ptrdiff_t.

    printf(" p is %p\n q is %p\n p-q is :%td", p, q, p-q);`
    //            ^^        ^^
    

    See http://en.cppreference.com/w/c/io/fprintf for the valid format specifiers for the different types.

提交回复
热议问题