Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we find out in which element in an array the address and value came from in c++

For example: int a[4] = {2, 4, 34}

Lets say the address of a[0] is at 2000 and we know the value of the element at a[0] is 2.

Given only a memory address and a value of an element, is it possible to determine the position of the element in the array?

If so, please provide an example on how to do this.

like image 748
Ottoman Avatar asked Nov 18 '25 08:11

Ottoman


1 Answers

Is this what you are looking for? Just using some pointer arithmetic;

int main ()
{
    int ary[] = { 1, 2, 3, 5 };

    int * address_of_2 = &ary[ 1 ];

    int index_of_2 = address_of_2 - ary;

    return 0;
}
like image 141
Catalyst Avatar answered Nov 19 '25 21:11

Catalyst