简体   繁体   中英

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.

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;
}

The memory location will be unique for each element in the array. So yes, if you know the memory location, you can iterate through the array and simply find when the reference equals your value.

for (int i=0; i < arr_size; i++) {
     if (&arr[i] == address && arr[i] == *address) {
        cout << i << endl;
        break;
    }
}

If given an array, the size of the array and type of element(ie integer), than yes, given also the address of an element and the value, you could sort through the array and find its position. Note the significance that the array block is contiguous.

array = array;
n = sizeof(array)/sizeof(*array);
oAddress = array;
fAddress = array + n * sizeof(*array);

locOfElement = (elementAddress - oAddress) / (fAddress - oAddress) * n; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM