在 c99 中,我的理解是比较两个不指向同一聚合的指针会导致未定义的行为。给定一个聚合 A,一个已知指向 A 内的指针 p_good,以及一个可能指向也可能不指向 A 内的指针 p_unknown,是否有可能构建一个具有定义行为的可移植测试,以确定比较 p_good 和p_未知?
显然,这个测试本身不能与比较指针的限制相冲突。
我怀疑答案是否定的,但我很乐意以其他方式显示。
最佳答案
你评论了:
Another way to frame the question would be like this: Given the definition of an aggregate 'A' and a pointer p, is it possible to answer the question 'does p point within A' without violating the rule on inequality testing of pointers to different aggregates
我可以有意义地解释这一点的唯一方法是,你要么有一个 Aggregate type
类型的对象,要么有一个指向它的指针。那么答案很简单:
伪代码:
bool p_in_A = false;
for (each element in Aggregate A)
if (&element == p)
p_in_A = true;
无法判断杂散指针是否属于未知的聚合对象(或指向聚合中“之间”的元素)。
关于C99:是否可以方便地确定两个指针是否指向同一聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165288/