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

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

Let's say the address a[0]

is in 2000

, and we know that the value of the at element a[0]

is 2

.

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

If yes, please provide an example of how to do this.

+3


source to share


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

      

+3


source


The memory location will be unique for each element in the array. So yes, if you know the memory location, you can loop over the array and just find when that reference is equal to your value.



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

      

+1


source


If given an array, array size, and element type (i.e. integer) than yes, given the element address and value, you can sort the array and find its position. Note that the array is contiguous.

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

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

      

0


source







All Articles