如何为数组分配不同的地址
How can I assign a different address to an array?
我想将数组传递给函数,然后将该数组变量完全指向该函数中的新地址。
我意识到数组在传递给函数时表现为指向其第一个元素地址的指针,那么为什么 main 中我的数组变量的地址不会改变呢?
#include <iostream>
using namespace std;
void passArrayByReference(int * array) { //passing array as. pointer should let us modify it's address, correct?
cout << "Address of array in function is: " << array << endl;
int * localArray = new int [2];
//put some dummy values in our localArray
localArray[0] = 9;
localArray[1] = 9;
array = localArray;
cout << "Address of array in function is now: " << array << endl;
}
int main()
{
int * array = new int [2];
int totalElements = 2;
//put some initial values into our dynamic 1D array
array[0] = 0;
array[1] = 1;
//print our initial values
for(int i = 0; i < totalElements; i++)
cout << array[i] << endl;
cout << "Address of array in main: " << array << endl;
passArrayByReference(array);
cout << "Address of array in main: " << array << endl;
return 0;
}
你走在正确的轨道上,但你只需要在你的函数头中包含"&"符号。"&"符号用于通过引用传递参数,而不是通过值传递。
在这种情况下,您将地址通过引用传递给数组的第一个元素,这意味着您可以在函数中修改该地址,并且更改将反映在您的主函数中。
#include <iostream>
using namespace std;
void passArrayByReference(int * &array) {
cout << "Address of array in function is: " << array << endl;
int * localArray = new int [2];
//put some dummy values in our localArray
localArray[0] = 9;
localArray[1] = 9;
array = localArray;
cout << "Address of array in function is now: " << array << endl;
}
int main()
{
int * array = new int [2];
int totalElements = 2;
//put some initial values into our dynamic 1D array
array[0] = 0;
array[1] = 1;
//print our initial values
for(int i = 0; i < totalElements; i++)
cout << array[i] << endl;
cout << "Address of array in main is: " << array << endl;
passArrayByReference(array);
cout << "Address of array in main is now: " << array << endl;
//now print the values of our 'new' array
cout << "The values of array are now:" << endl;
for(int i = 0; i < totalElements; i++)
cout << array[i] << endl;
return 0;
}
首先,您必须逐个指针或引用传递指针才能对其进行持久更改 - 即更改原始指针,而不仅仅是在函数体中复制它:
void passArrayByReference(int *&array) {
//...
array = new_address;
std::cout << "Address of array in function is now: " << array << std::endl;
}
// and here it is the same
其次,您应该分配有效的地址new_address
,并注意在进入函数之前array
引用的内存,以避免内存泄漏。
指针
也是变量。这就是为什么您需要将array
作为对passArrayByReference
的引用传递,这样您就不会只是修改它的副本。
void passArrayByReference(int *&array)
相关文章:
- 将数组的地址分配给变量并删除
- 将地址分配给本地指针后,公共对象的变量将消失
- LLVM 传递以在特定地址分配内存
- 如何按顺序或在指定的地址分配内存?
- C 内存地址分配
- 有没有其他方法可以将地址分配给指针变量
- 我可以将文件描述符的地址分配给变量
- 将地址分配给结构内的指针
- 如何将数组的地址分配给指针
- 尝试将派生类对象地址分配给基类指针的向量
- 将派生的对象地址分配给基础指针和调用击路仪的机制
- 在 c++ 中使用指针访问 2d 数组,如何将地址分配给指针
- 查询与将地址分配给共享_ptr有关
- 将非常量的地址分配给常量指针
- 类的地址分配
- 将 int 自己的地址分配给其值
- 如果指定了参数,如何将地址分配给函数指针
- std::bad_alloc从引用的地址分配指针
- 在该地址c++分配之前和之后相等指针之间的差异
- 在窗口中的特定地址分配数据