Returned Pointer gives different address?!?!

Hi all!

I apologise if this is a wall of text...

I have been going through the "C++ for dummies book". On page 125 (should any of you have it) it states that in a function you can use the heap memory to create a portion of memory for, say, a double. And that once you leave the function, even though the variabl is out of scope, the heap will retain the portion for the double.

However I am using pointers (as per the example on the page) to check this. I am printing to the console the address from the pointer which is looking at the new heap block. I am then returning that pointer to main, where I am then again printing the address to the console.

The problem is that both pointers are looking at different areas of memory. I was under the impression that the heap keeps the block and therefore both the original (dppointer) and the returned pointer (dpmydouble) would be looking at that same block!

What am I doing wrong?

P.S. I'm using the version of bundled Code::Blocks and GNU GCC compiler that came with the book.

To assist with this conundrum, here is my code and ouputs.:


CODE:
// MorePointerTesting
// This program is to test the use of 'new' and 'delete'

#include <iostream>
#include <cstdlib>

using namespace std;

double* fndoublereturn (void);

int main()
{
double* dpmydouble = fndoublereturn();

cout << "dpmydouble points to: " << dpmydouble
<< endl;

delete dpmydouble;
dpmydouble = 0;

return 0;
}
//-----------------------------------------------//
// Functions Below //
//-----------------------------------------------//
double* fndoublereturn (void)
{
double* dppointer = new double;
cout << "Debug from fndoublereturn is: " << &dppointer << endl;
return dppointer;
}


OUTPUT (Average):
Debug from fndoublereturn is: 0x22feec
dpmydouble points to: 0x360fd0

Process returned 0 (0x0) execution time : 0.093 s
Press any key to continue.
&dppointer is the address of the pointer.
dppointer is the value pointed to. You should be using this in your code.
Oh my word... that is totally right!

Thank you so much! That ACTUALLY helps make it all clearer - Thanks again!

P.S. for anyone reaing this thread removing the '&' from in front of dppointer in function fndoublereturn() means both pointers return the same address!

Thanks again kbw!
Topic archived. No new replies allowed.