How does pointer comparison work in C? Is it ok to compare pointers that don't point to the same array?

前端 未结 7 1071
野的像风
野的像风 2020-12-16 10:07

In K&R (The C Programming Language 2nd Edition) chapter 5 I read the following:

First, pointers may be compared under certain circumstances. If

7条回答
  •  囚心锁ツ
    2020-12-16 10:09

    Pointers are just integers, like everything else in a computer. You absolutely can compare them with < and > and produce results without causing a program to crash. That said, the standard does not guarantee that those results have any meaning outside of array comparisons.

    In your example of stack allocated variables, the compiler is free to allocate those variables to registers or stack memory addresses, and in any order it so choose. Comparisons such as < and > therefore won't be consistent across compilers or architectures. However, == and != aren't so restricted, comparing pointer equality is a valid and useful operation.

提交回复
热议问题