Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

(Note that the subtraction is between two pointers to "struct A", not two chars. In the snippet "char" is used simply because it's 1 byte; one could also use int8_t, assuming a byte is 8 bits long.)

It's a fact about how the C language does pointer arithmetic.

For instance, suppose you have an array of many 64-bit integers, and a pointer to one of the elements of the array:

    int64_t arr[100];
    int64_t *p;
    p = &arr[50];
Now, the value of p is a certain address in memory. As each element of the array takes 8 bytes (64 bits = 8 bytes), the address of the next element of the array is 8 bytes past the location of p. In some languages (including assembly), you have to refer to this address by manually adding 8 to the address stored in p. In C, to refer to the next element of the array, you write "p + 1", and the compiler translates that into adding 8 bytes.

Conversely, if you give the new pointer a name:

    int64_t *q;
    q = p + 1;
then you expect (q - p) to be 1, not 8 (even though the value stored in q is 8 more than the value stored in p).

That is, when subtracting pointers (of the same type), the result implicitly divides by the size of the type. In the code example in the blog post, as the size of "struct A" is 7 bytes, subtracting two pointers to A will subtract the memory addresses and divide by 7.

If that wasn't clear, see this sentence on Wikipedia: https://en.wikipedia.org/w/index.php?title=Pointer_(computer... or the answers to this question: https://stackoverflow.com/questions/3238482/pointer-subtract... or play with it yourself here: https://godbolt.org/z/M6PEWYeYx



Ok, I’ve looked at this about five separate times and think that I finally get it. Thank you so much.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: