Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
914 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...