Getting index from array-value in O(1)


I've got a dyn. allocated array like this: MyClass* myarray = new MyClass[10];

At some point I have a pointer that points to one element in myarray but not the index.
I need this index. My naive approch is simply iterating and comparing by value:

int findIndex(MyClass* ptr) {
    for(int i = 0; i < 10; i++) {
        if(&myarray[i] == ptr) return i;
    return -1;

This runs in O(n) worst case. I need (if possible) O(1). I think thats possible with pointer arithmetics but I don't know anything about that.

Can someone help me?
Thanks in advance!
Where have you declared myarray[] in your function?
Not sure if this is acceptable practice or not, but you could just subtract myarray from ptr int i = ptr - myarray;. So be cautious with this approach. Example:

Also, if you have pointed ptr at an element in myarray, would you not have known the index of that element at the time you assigned it to ptr (so you don't have to do any searching)?
myarray is declared as a member, as is findIndex.

I'll test your solution Danny essentially covers both already mentioned methods.
Topic archived. No new replies allowed.