检查指针是否指向数组内 [英] checking if pointer points within an array

查看:48
本文介绍了检查指针是否指向数组内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以检查给定的指针是否指向数组中的对象,由其边界指定吗?

Can I check whether or not a given pointer points to an object within an array, specified by its bounds?

template <typename T>
bool points_within_array(T* p, T* begin, T* end)
{
    return begin <= p && p < end;
}

或者如果 p 指向数组边界之外,指针比较是否会调用未定义的行为?在这种情况下,我该如何解决问题?它适用于空指针吗?还是无法解决?

Or do the pointer comparisons invoke undefined behavior if p points outside the bounds of the array? In that case, how do I solve the problem? Does it work with void pointers? Or is it impossible to solve?

推荐答案

虽然比较只对数组内的指针和越过末尾"的指针有效,但使用 set 或 map 以指针作为键,它使用 std::less

Although the comparison is valid only for pointers within the array and "one past the end", it is valid to use a set or map with a pointer as the key, which uses std::less<T*>

早在 1996 年,就在 comp.std.c++

There was a big discussion on this way back in 1996 on comp.std.c++

这篇关于检查指针是否指向数组内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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