开发者

Taking the address of a pointer

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 开发者_如何学JAVAwaited 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.


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?


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


reset the pointer p's position.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜