检查指针是否指向给定数组 [英] Check if pointer points to given array

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

问题描述

因此,我有一个函数返回一个指向数组A中元素的指针.我有另一个函数将该指针作为参数.但是,我需要该函数能够处理可能将其传递给完全任意的指针的可能性.

So I have a function that returns a pointer to an element in an array A. I have another function that takes that pointer as a parameter. However, I need that function to be able to deal with the possibility that it may be passed a completely arbitrary pointer.

有没有一种方法可以检测指针是否指向结构内的某个位置?在这种情况下,我的数组A是什么?

Is there a way to be able to detect if a pointer points somewhere within a structure? In this case, my array A?

我见过关于C ++的类似问题,但关于C ++却没有.

I've seen similar questions regarding C++, but not with C.

推荐答案

唯一可移植的方法是对指针的所有可能有效值使用相等性测试.例如:

The only portable way is to use an equality test against all of the possible valid values for the pointer. For example:

int A[10];

bool points_to_A(int *ptr)
{
    for (int i = 0; i < 10; ++i)
        if ( ptr == &A[i] )
             return true;

    return false;
}

请注意,使用带有两个指针的关系运算符(例如<)或减法是未定义的行为,除非两个指针实际上确实指向同一数组的元素(或指向末尾的元素).

Note that using a relational operator (e.g. <), or subtraction, with two pointers is undefined behaviour unless the two pointers actually do point to elements of the same array (or one past the end).

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

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