i have some trouble in dynamic allocation with 'new' and reference. Please see a simple code below.
#include<iostream>
using namespace std;
void allocer(int *pt, int *pt2);
int main()
{
int num = 3;
int num2 = 7;
int *pt=#
int *pt2 = &num2;
allocer(pt, pt2);
cout << "1. *pt= " << *pt << " *pt2= " << *pt2 << endl;
cout << "2. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
}
void allocer(int *pt, int *pt2)
{
int temp;
temp = *pt;
pt = new int[2];
pt[0] = *pt2;
pt[1] = temp;
cout << "3. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
}
What i want to do is to make the function 'allocer' get 2 arguments which are the int pointer and allocate memory on one of them. As you can see, *pt becomes an array to take 2 integers. Inside of the function it works well which means the sentence that i marked 3. printed as what i intended. However, 1, 2 doesn't work. 1 prints the original datas(*pt= 3, *pt2= 7), 2 prints error(*pt= 3, *pt2= -81203841). How to solve it?
You are passing in the
ptandpt2variables by value, so any new values thatallocerassigns to them is kept local toalloceronly and not reflected back tomain.To do what you are attempting, you need to pass
ptby reference (int* &pt) or by pointer (int** pt) so thatallocercan modify the variable inmainthat is being referred to.Also, there is no good reason to pass
pt2as a pointer at all sinceallocerdoesn't use it as a pointer, it only dereferencespt2to get at the actualint, so you should just pass in the actualintby value instead.Try something more like this:
Or