A quick note: a pointer is a special type of variable that points to an address instead of a regular value.
loopy is a regular variable that points to a value, in this case we set it to 3: loopy = 3;pointerLoopy is a pointer, so it needs to be set to an address. In order to get the address of loopy we use the & operator: pointerLoopy = &loopy;You can't just set a pointer to a regular variable because the types don't match. Trying
int* pointyLoopy = loopy;Will get you
error: invalid conversion from ‘int’ to ‘int*’I know this sounds confusing so:
//allows you to change the value the pointer points to
//but NOT the pointer itself
//you can't make it point somewhere else
void passerP(int* pointyLoopy)
{
//dereference the pointer to change the value of loopy
*pointyLoopy = 5;
printf("Inside passerP: loopy = %i\n", *pointyLoopy);
int loopier = 2;
pointyLoopy = &loopier;
printf("Inside passerP: pointyLoopy = %i\n", pointyLoopy);
}
//allows you to change what the POINTER is
// and the value it points to
void passerPR(int*& pointyLoopy)
{
*pointyLoopy = 7;
printf("Inside passerPR: loopy = %i\n", *pointyLoopy);
int loopier = 4;
pointyLoopy = &loopier;
printf("Inside passerPR: pointyLoopy = %i\n", pointyLoopy);
}
int main (int argc, char const *argv[])
{
int loopy = 3;
int* pointyLoopy = &loopy;
printf("\nloopy = %i\n", loopy);
printf("pointyLoopy = %i\n", pointyLoopy);
passerP(pointyLoopy);
printf("loopy = %i\n", loopy);
printf("pointyLoopy = %i\n", pointyLoopy);
printf("\nloopy = %i\n", loopy);
printf("pointyLoopy = %i\n", pointyLoopy);
passerPR(pointyLoopy);
printf("loopy = %i\n", loopy);
printf("pointyLoopy = %i\n\n", pointyLoopy);
return 0;
}
This code prints out:
loopy = 3
pointyLoopy = -1073743396
Inside passerP: loopy = 5
Inside passerP: pointyLoopy = -1073743444
loopy = 5
pointyLoopy = -1073743396
loopy = 5
pointyLoopy = -1073743396
Inside passerPR: loopy = 7
Inside passerPR: pointyLoopy = -1073743444
loopy = 7
pointyLoopy = -1073743444
Notice that for the first function, the value of loopy changes, but the address that pointyLoopy pointed to was lost--it stayed as -1073743396 regardless of what we did inside the function passerP. In the second, the value of loopy changes AND the address that pointyLoopy pointed to changed from -1073743396 to -1073743444.
This is useful if you are passing around a pointer that you needed to delete in a function. If you didn't use *& the delete would not stick and the pointer would instead revert to whatever the calling function thought the value was....thus it never really was deleted and you have a memory leak.
Another use would be if you are creating a pointer = NULL in main, and wanted to load it up with something in the function, then use that value in main later on.
However, if you only want to change the value that the pointer points to (e.g. loopy) then you can use * instead of *&.

0 comments:
Post a Comment