The following is a small scale example of the problem I am facing. In the example below I use int pointers but in my own code I am really using a pointer to another class.
I do need/want to be able to pass multiple pointers to the same method and I do not really want to write a specific method for each pointer.
When I run the code, of course, I do not get the expected results.
I think I have narrowed down the problem but am not sure how to fix it. Since everything in C++ is pass by value, the pointers that I am passing around need to be pass by reference. I did try changing my methods to call by reference like this in the below method:
int** getIntPointer() {return &p1;}
void initializeP1(int **&ip,int n) and void initializeP1(int **ip,int n)
But nothing seems to be working.
Does anyone have a clue how to fix this?
Thank you
#include <iostream>
using namespace std;
class Test {
private:
int *p1;
int *p2;
int sizeP1;
int sizeP2;
public:
int** getIntPointer() {return &p1;}
void initializeP1(int **&ip,int n){
sizeP1=n;
*ip=new int[n];
for(int i=0;i<n;i++)
*ip[i]=i;
}
void printP1() {
for(int i=0;i<sizeP1;i++)
cout<<p1[i]<<" ";
}
};
int main() {
Test t;
int** p = t.getIntPointer();
t.initializeP1(*&p,10);
t.printP1();
return 0;
}
This line is wrong:
The
[]operator has higher precedence than the*operator, so that line is equivilent to this:You need to change it to this instead: