view raw
Bob Bob - 6 months ago 36
C Question

Check if pointer points to given array

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.

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

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. <) with two pointers is undefined behaviour unless the two pointers actually do point to elements of the same array (or one past the end).