[英]Is it UB to compare (for equality) a void pointer with a typed pointer in C?
我有一个类型化指针typed
,它是使用指针算术初始化的,以指向数组中的 object。 我还有一个 function 需要两个指针参数,第一个类型与上述指针相同,第二个是void *
(参见下面代码中的myfunc()
)。
如果我将typed
作为第一个参数传递,另一个指针类型与第二个参数typed
相同,然后在 function 中比较它们是否相等,那是未定义的行为吗?
#include <stdio.h>
typedef struct S {int i; float f;} s;
void myfunc(s * a, void * b)
{
if (a == b) // <-------------------------------- is this UB?
printf("the same\n");
}
int main()
{
s myarray[] = {{7, 7.0}, {3, 3.0}};
s * typed = myarray + 1;
myfunc(typed, &(myarray[0]));
return 0;
}
更新:好的,所以我在上面发布我的问题后一天回来,有两个很好的答案(感谢@SouravGhosh 和@dbush)。 一个比另一个早了不到一分钟(,),但从第一个评论的外观来看。 答案最初是错误的,只有在第二个答案发布后才更正? 我接受哪一个? 在这种情况下,是否有一种协议可以接受一个答案而不是另一个答案?
不,这不是未定义的行为。 这是在等式运算符约束的规范中允许并明确定义的。 引用C11
,第 6.5.9 章
一个操作数是指向 object 类型的指针,另一个是指向 void 的限定或非限定版本的指针;
以及同一章的第 5 段
[...] 如果一个操作数是指向 object 类型的指针,而另一个是指向 void 的限定或非限定版本的指针,则前者将转换为后者的类型。
这种比较是明确定义的。
当通过==
将void *
与另一个指针类型进行比较时,另一个指针将转换为void *
。
此外, C 标准的第 6.5.9p6 节说明了以下关于与==
进行指针比较的内容:
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function,both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.
这里没有提到未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.