在c++中,我们如何找出地址和值来自数组中的哪个元素

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

本文关键字:数组 元素 c++ 我们 地址 何找出      更新时间:2023-10-16

例如:int a[4] = {2, 4, 34}

假设a[0]的地址在2000,并且我们知道a[0]处的元素的值是2

只给定一个内存地址和一个元素的值,是否可以确定元素在数组中的位置?

如果是,请提供一个如何做到这一点的示例。

这就是您想要的吗?只是使用一些指针运算;

int main ()
{
    int ary[] = { 1, 2, 3, 5 };
    int * address_of_2 = &ary[ 1 ];
    int index_of_2 = address_of_2 - ary;
    return 0;
}

数组中每个元素的内存位置都是唯一的。所以,是的,如果你知道内存位置,你可以遍历数组,只需找到引用何时等于你的值。

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

如果给定一个数组,则数组的大小和元素的类型(即整数(,而不是yes,还给定元素的地址和值,则可以对数组进行排序并找到其位置。请注意数组块是连续的。

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