取指针的地址

时间:2010-09-06 10:23:32

标签: c++ pointers

如果我声明以下变量:

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++ << " ";
}

为我提供了不同的输出(一组不同的地址):

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

为什么呢?它们在语义上是不相同的吗?

编辑:

好吧,我向所有回答此问题的人致歉,我没有原始代码,这是我在家里做的测试,事实证明我从我的项目中删除了该代码。 (我的宽带还没有连接,所以我一直等到工作发布这个)。无论如何 - 我很确定我忘了初始化p。但问题是“它们在语义上是否相同?”已经回答了。感谢。

4 个答案:

答案 0 :(得分:13)

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';

给我相同的地址。您是否意外忘记了中间的p = array;

答案 1 :(得分:4)

如果您记得在第二次循环之前重置p,它们会给出相同的结果。

答案 2 :(得分:0)

重置指针p的位置。

答案 3 :(得分:-1)

优先顺序首先是'++',然后是'*',最后是'&amp;'。

因此p++将输出array[0]的地址,而&*p++将首先递增p,但这是后缀!因此p的值(而不是p + 1的值)将被赋予*然后到&amp;,所以它们是相同的

示例:

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
相关问题