How to compare C pointers?

后端 未结 6 1322
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 08:57

Recently, I wrote some code to compare pointers like this:

if(p1+len < p2)

however, some staff said that I should write like this:

6条回答
  •  Happy的楠姐
    2020-12-09 09:02

    The existing answers show why if (p2-p1 > len) is better than if (p1+len < p2), but there's still a gotcha with it -- if p2 happens to point BEFORE p1 in the buffer and len is an unsigned type (such as size_t), then p2-p1 will be negative, but will be converted to a large unsigned value for comparison with the unsigned len, so the result will probably be true, which may not be what you want.

    So you might actually need something like if (p1 <= p2 && p2 - p1 > len) for full safety.

提交回复
热议问题