The reference isn't the problem. It's your dynamic memory management that is dreadfully broken.
#include <iostream>
using namespace std;
void test(int *&ptr);
int main(void)
{
int *ptr = new int[1]; // allocates a sequence of 1
ptr[0] = 100;
cout << ptr[0];
test(ptr); // sends pointer to sequence by reference to test
cout << ptr[0] << '\t' << ptr[1];
}
void test(int *&ptr)
{
int *tmp = new int[2]; // allocates a sequence of size 2
tmp[0] = 1;
tmp[1] = 2;
int *tmp2 = ptr; // stores original passed-in pointer to tmp2
ptr = tmp; // assigns new sequence pointer to reference argument (leaks original)
cout << ptr[0] << '\t' << ptr[1];
delete[] ptr; // deletes the new sequence. (leaves dangling pointer)
}
What you seem to be trying to do is this:
#include <iostream>
using namespace std;
void test(int *&ptr);
int main(void)
{
int *ptr = new int[1];
ptr[0] = 100;
cout << ptr[0] << '\n';
test(ptr);
cout << ptr[0] << '\t' << ptr[1] << '\n';
delete [] ptr;
}
void test(int *&ptr)
{
delete [] ptr; // delete original sequence
ptr = new int[2]; // create new sequence
ptr[0] = 1;
ptr[1] = 2;
}
Stop Using Raw Pointers
Alternatively, use smart pointers to manage this.
#include <iostream>
#include <memory>
using namespace std;
void test(std::unique_ptr<int[]>& ptr);
int main(void)
{
std::unique_ptr<int[]> ptr = std::make_unique<int[]>(1);
ptr[0] = 100;
cout << ptr[0] << '\n';
test(ptr);
cout << ptr[0] << '\t' << ptr[1] << '\n';
}
void test(std::unique_ptr<int[]>& ptr)
{
ptr = std::make_unique<int[]>(2);
ptr[0] = 1;
ptr[1] = 2;
}
Or better still, just use a std::vector<int>