Pointers and References
declaring the variables:
int A; int *pA; int B; int *pB;
at this point, A is a container for an integer, and B is a container for a pointer to an integer.
in the body of the code, a “*” can be seen as “the value pointed to by”, and “&” can be seen as “the address of”, as in (using the above delarations):
A = 100; //directly sets the value of A pA = &A; //now pA contains the address of A pB = pA; //now pB contains the value of pA, which is the address of A B = *pB; //now B contains the value that is pointed to by pB
now both A and Bcontain “100″, and both pA and pB contain the location of A.
cout << "A: " << A << endl; //displays value in A cout << "B: " << B << endl; //displays value in B cout << "pA: " << pA << endl; //displays address in pA cout << "pB: " << pB << endl; //displays address in pB cout << "*pA: " << *pA << endl; //displays value pointed to by pA cout << "*pB: " << *pB << endl; //displays value pointed to by pB cout << endl;
would show something like the following (note that [ADDRESS] would actually be a memory location):
A: 100 B: 100 pA: 0x[ADDRESS] pB: 0x[ADDRESS] *pA: 100 *pB: 100
at this point, setting the value held by A could be done in any of the following ways:
A = 200; *pA = 200; *pB = 200;
*pB can be used to set the value of A because pB contains the address of A.
note that B contains the same value as is in A, but is now independant of it. in the above example, A was set, then pA was set to it’s address, then pB was set to the contents of pA, then B was set the the value pointed to by pB.
Leave a comment