如何为数组分配不同的地址

How can I assign a different address to an array?

本文关键字:地址 分配 数组      更新时间:2023-10-16

我想将数组传递给函数,然后将该数组变量完全指向该函数中的新地址。

我意识到数组在传递给函数时表现为指向其第一个元素地址的指针,那么为什么 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)