测试迭代指针之间的关系是否安全? [英] Is it safe to test relations between pointers for iteration?

查看:11
本文介绍了测试迭代指针之间的关系是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Please consider an array of Thing. It's a kind of stack.

It is pointed to by thingsBottom, and its empty end is pointed to by thingsTop.

EDIT: Every time I want push something onto the list, I do *thingsTop = newThing; thingsTop++;.

I'd like to iterate it from the end to the beginning using pointers, like so:

for (Thing* thing = thingsTop - 1; thing >= thingsBottom; thing--) {
    doSomething(*thing);
}

Is this guaranteed to always work, regardless of the specific C implementation used?

Is it safe to say thing >= thingsBottom?

解决方案

Is this guaranteed to always work, regardless of the specific C implementation used?

Is it safe to say thing >= thingsBottom?

No, and not unconditionally.

The problem with your approach is that it produces undefined behavior to compute a pointer value that would be before the beginning of the array on which that pointer is based, and pointer comparisons are valid only for pointers into, or just past the end of, the same array. "Just before the beginning" does not have any special status or provision.

You can write such a loop; you just need to test before you decrement:

for (Thing* thing = thingsTop; thing > thingsBottom; ) {
    thing--;
    doSomething(*thing);
}

这篇关于测试迭代指针之间的关系是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆