请考虑一组 Thing
。这是一种堆栈。
thingsBottom
指向它,thingsTop
指向它的空端。
编辑: 每次我想将某些内容推送到列表中时,我都会执行 *thingsTop = newThing; thingsTop++;
.
我想使用指针从头到尾迭代它,如下所示:
for (Thing* thing = thingsTop - 1; thing >= thingsBottom; thing--) {
doSomething(*thing);
}
无论使用何种特定的 C 实现,这是否保证始终有效?
说 thing >= thingsBottom
安全吗?
最佳答案
Is this guaranteed to always work, regardless of the specific C implementation used?
Is it safe to say
thing >= thingsBottom
?
不,而且不是无条件的。
你的方法的问题在于它会产生未定义的行为来计算一个指针值,该指针值将在该指针所基于的数组的开头之前,并且指针比较仅对指向或刚好超过结尾的指针有效的,同一个数组。 “就在开始之前”没有任何特殊的地位或规定。
您可以编写这样一个循环;你只需要在递减之前进行测试:
for (Thing* thing = thingsTop; thing > thingsBottom; ) {
thing--;
doSomething(*thing);
}
关于c - 测试迭代指针之间的关系是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56748757/