gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:49 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com