I’m currently going over pointers in class and our textbook is confusing me a little bit. They start off by saying that following example copies the value in the place pointed to by money into the place pointed to by myMoney:
*myMoney = *money;
Then the next example copies the value in money into myMoney
myMoney = money;
This second example causes a memory leak because the original location that *myMoney pointed is no longer accessible. Is this because the memory that used to hold the pointer is now an actual float value instead of a memory address?
Now the part that confuses me a little is in the next part when they are showing a different declaration. Full example:
char alpha[20];
char *alphaPtr;
char *letterPtr;
vod Process(char []);
.
.
alphaPtr = alpha;
letterPtr = &alpha[0];
Process(alpha);
Since the book says that
myMoney = money;
will create a memory leak because it severs the link between the pointer and it’s pointed to address, will
alphaPtr = alpha;
cause a memory link also? Shouldn’t they have declared it like
char *alphaPtr = *alpha;
Things to remember:
myMoneyandmoneyare pointers, somyMoney = money;copies one pointer over another. Now you have two pointers pointing at the same thing (whatmoneypointed to), and nothing pointing at whatmyMoneyused to point at (this is a memory leak).*myMoneyand*moneyare the values pointed to by the pointers (because*dereferences a pointer to get what it’s pointing to), so*myMoney = *money;copies whatmoneypoints to over whatmyMoneypoints to; the pointers themselves did not change.alphais an array, which can be degraded into a pointer to the first element in the array.alphaPtrbecause it wasn’t pointing to anything in the first place.char *alphaPtr = *alpha;Would have been a much better way to write it, because thenalphaPtrdoesn’t spend any time uninitialized. Some compilers will even warn you when you declare uninitialized pointers like the textbook example.