vendredi 6 mars 2015

Modify the location a pointer points to in a C++ function


I am learning c++ and I have gotten stuck on modifying pointers of pointers. The problem is that I don't understand why my code works. What I am trying to do is modify where a pointer points to in a function. Then accessing that value in my main function. I tried quite a few attempts and this is the only way I got it to work.



#include <iostream>
using namespace std;
void changePP(int **ppint) {
int *n = new int;
*n = 9; //just a value for demonstration purposes
*ppint = n; //THE LINE IN QUESTION
delete n;
}
int main() {
int **ppint = NULL;
int *p = new int;
*p = 4; //another value for demonstrating
ppint = &p;
cout << **ppint << endl;
changePP(ppint);
cout << **ppint << endl;
}




So, the output is 4 and then a 9 on seperate lines. However, I am not sure about the line *ppint = n in the code. Why do I have to use the * to change where ppint points to in the changePP function but not in the main? Also why do I not have to use the & in the function? I can't seem to find an explanation that I can understand on the internet and I was wondering if someone could explain this for me? Thanks.




Aucun commentaire:

Enregistrer un commentaire