在c++中,我们如何找出地址和值来自数组中的哪个元素
How can we find out in which element in an array the address and value came from in c++
例如: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;
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int