1
votes

If I declare the following variables:

int array[10] = { 34, 43,12, 67, 34, 43,26, 98, 423,1 };
int * p = array;

Then, this loop:

for ( int i = 0; i < 10; i++ )
{
    std::cout << &*p++ << " ";
}

gives me different output ( a different set of addresses ), to this code:

for ( int i = 0; i < 10; i++ )
{
    std::cout << p++ << " ";
}

Why? Aren't they semantically equivalent?

EDIT:

Well, my apologies to everyone that answered this one, I don't have the original code, it was a test that I did at home and it turns out that I deleted that code from my project. ( my broadband is not yet connected, so I waited till I got to work to post this ). Anyway - I am pretty sure that I was forgetting to initialise p. But the question of "aren't they semantically equivalent?" has been answered. Thanks.

4
I think it is related to the precedence of operators. What happens if you add parenthesis ?Cedric H.
Post some output as well and the exact code. I think you will need to reinitialize p as a poster explained.dirkgently
@dirkgently - its possible - my original code is at home. oh no - I might have posted a duff question here. uh - oh.BeeBand
@BeeBand Don't worry about it - we all do it all the time. Myself more than anyone else it seems. Every time I come across a problem that I don't understand, I spend ages trying to work it out, then post it here and the first answer is something like "You've forgotten to return anything from that function." XD.Stephen
@BeeBand: Nevertheless, it's prompted an interesting discussion below!Oliver Charlesworth

4 Answers

13
votes
int array[10] = { 34, 43,12, 67, 34, 43,26, 98, 423,1 };
int * p = array;

for ( int i = 0; i < 10; i++ )
{
    std::cout << p++ << " ";
}
p = array;
std::cout << '\n';
for ( int i = 0; i < 10; i++ )
{
    std::cout << &*p++ << " ";
}
std::cout << '\n';

Gives me the same addresses. Did you accidentally forget p = array; in between?

4
votes

If you remember to reset p before the second loop, they give the same result.

0
votes

reset the pointer p's position.

-1
votes

The order of precedence is '++' first, then '*' and finally '&'.

So p++ will output the adresse of array[0] and &*p++ will first increment p, but this is postfix ! So the value of p (and not the value of p+1) will be given to * and then to &, so these are the same

Example:

std::cout << p << std::endl; // Output the adress of p
std::cout << &*p++<<std::endl; // p is increment but it is postfix, so value of p is used and printed
std::cout << &*++p<<std::endl; // p has been increment before and is then incremented again
std::cout << p++ << std::endl; // p has been incremented before, but here p is used first, then incremented