Assigning pointers to a new memory location

for(int x = 0; x < 2; x++)
{
int* xx = new int;
xx = &x;
cout << "Location of xx: " << &xx << endl;
}

What I'm trying to do, is every time I run through this loop xx is storing what x contains in a new int place. Right now when I run this, it is giving me same memory location in the output both times. What can I do so that it's creating a new one each time?
You allocate memory, then get ride of your handle to it (xx). The address your printing is that of x, and not the memory freshly allocated to xx. Just remove the 3rd line.
Thanks. I slept on it and realized I was kind of asking the wrong question.

for(int x = 0; x < 2; x++)
{
int* xx = new int;
*xx = x;
cout << "xx points to: " << &*xx << endl;
}
This gives me the results. I realized what I was wanting to do was have xx place each value of x into a new memory location then see where it was stored. Sometimes stepping away from a problem is the best thing to help you find a solution. Thanks for you help.
For the record, "&*xx" is equivalent to "xx". Here, 'xx' is an address. '*xx' is 'the value stored at address xx'. '&*xx' would be 'the address of the value stored at address xx'. Which is redundant.
Thanks. I figured there was a more elegant way to do it, but I was so happy to finally get the results I'd been wanting that I didn't care.

UPDATE: Yup. I went band and changed it and it worked. Thanks again.
Last edited on
Topic archived. No new replies allowed.