c - 比较两个指针有什么限制?

标签 c pointers compiler-errors equals-operator relational-operators

int a=40,b=34;
int *iptr1,*iptr2;                        
iptr1 = &a;
iptr2 = &b;        
printf("\n Equal condition of two pointers=%d", (ip1 == ip2));    //no error 

char name1[20], name2[20];
char *p1 = name1;
char *p2 = name2;
if(p1 > p2) /*Error*/ 

为什么关系操作有错误/警告,而比较操作没有错误/警告?

最佳答案

您只能对来自同一数组或同一聚合对象的指针执行关系操作(<><=>=)。否则,它会导致 undefined behavior .

引用 C11 ,第 6.5.8 章,关系运算符,第 5 段

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

在你的代码中,

  if(p1>p2)

是尝试比较两个不属于同一数组对象的指针,既不是同一聚合对象的成员。因此,它会触发警告。

但是,为了比较,没有这样的约束,所以像 (ip1==ip2) 这样的表达式完全没问题。

关于c - 比较两个指针有什么限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942604/

相关文章:

c# - 为什么我可以将 1 作为 short 而不是 int 变量 i 传递?

java - Java程序: unmappable character for encoding UTF8的编译错误

c - 如何用 0(零)填充整数?

c - 即使在基本情况下调用递归函数时也会无限循环

c - 网络 write() 是否可能失败但 poll() 未检测到

C - Code::Blocks 13.12:哪一个可以正常工作,或者两者都可以?两者有区别吗?还是C标准允许的?

c - C 中返回值类型不匹配

c - 如何使用 malloc 在 ANSI - C 中声明动态整数数组并将输入整数放入其中?

pointers - 在 Rust 中返回指针时发生了什么?

spring - Spring Boot一周后编译JSP错误