Reputation: 21
I have created 2 dynamic arrays in the main function. I have passed both of them to the function by reference. Then I copy data from smaller dynamic array to the larger dynamic array. I delete the smaller dynamic array. Assign the address of the larger dynamic array to the smaller dynamic array. Now ideally the arr array should have size of 10. However, when I try to print the 6th element of the array in the main, it crashes. Please have a look at the code below:
#include <iostream>
#include <string>
using namespace std;
void func(string * arr, string * brr);
int main()
{
string* arr = new string[5];
arr[0] = "hello0";
arr[1] = "hello1";
arr[2] = "hello2";
arr[3] = "hello3";
arr[4] = "hello4";
string* brr = new string[10];
func(arr, brr);
for(int i = 0; i < 6; i++)
cout << arr[i] << endl;
return 0;
}
void func(string * arr, string * brr)
{
for(int i = 0; i < 5; i++)
brr[i] = arr[i];
for(i = 0; i < 5; i++)
cout << brr[i] << endl;
delete []arr;
arr = brr;
arr[5] = "hello5";
}
Upvotes: 2
Views: 5556
Reputation: 816
Set this signature for the function
void func(string * & arr, string * & brr)
Upvotes: 2
Reputation: 49803
@cnicutar correctly diagnosed the problem; you'll either need to pass arr by reference (reference to the POINTER, not the array), of have fund return the new value of arr, which the caller can assign.
Upvotes: 0
Reputation: 182619
This line has absolutely no effect for the caller:
arr = brr;
So after the call, arr
points exactly where it used to point before - to a now invalid memory area (because you deleted it).
If this would be a C question, I would advise you to use a pointer to a pointer (string **arr
). However, I feel this is nasty in a C++ program. Maybe you want to use a reference somewhere ?
Upvotes: 3