测试指针之间的关系以进行迭代是否安全?

编程入门 行业动态 更新时间:2024-10-26 10:28:53
本文介绍了测试指针之间的关系以进行迭代是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请考虑一个Thing数组.这是一种堆栈.

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

由thingsBottom指向,其空端由thingsTop指向.

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

编辑:每次我想将某些内容推入列表时,我都会执行*thingsTop = newThing; thingsTop++;.

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); }

无论使用哪种特定的C实现,这是否可以保证始终有效?

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

说thing >= thingsBottom是否安全?

推荐答案

这可以保证始终运行,而不管特定的C语言如何 实施?

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

说thing >= thingsBottom是否安全?

不是,不是无条件的.

您的方法的问题在于,它会产生未定义的行为来计算指针值,该值将在该指针所基于的数组的开始之前,并且指针比较仅对进入或刚刚结束的指针有效的,相同的数组. 就在开始之前"没有任何特殊的地位或规定.

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); }

更多推荐

测试指针之间的关系以进行迭代是否安全?

本文发布于:2023-10-29 07:44:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539122.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   迭代   关系   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!