배열을 함수에 전달한 다음 해당 배열 변수를 상기 함수 내에서 새 주소로 지정하려고합니다.배열에 다른 주소를 어떻게 할당합니까?
배열이 함수에 전달 될 때 첫 번째 요소의 주소에 대한 포인터로 동작한다는 것을 알고 있습니다. 그렇다면 왜 배열에서 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;
}
배열에 할당 할 수 없습니다. 그러나 * 포인터 *에 할당하고 있으므로 가능합니다. 그러나 배열과 포인터를 혼동하지 마십시오. – juanchopanza
지금 메모리 누수가 있습니다. 새로운 주소를 할당하기 전에 이전 배열을'delete []'해야하고, 더 이상 필요하지 않을 때 새 주소를'delete [] '해야합니다. – woytaz
배열을 참조로 전달하지 않았으므로 값을 전달했습니다. –