这段代码的输出是什么?

What is the out put of this code any why?

本文关键字:输出 是什么 代码 段代码      更新时间:2023-10-16

我在c++中有一个函数,我知道会是什么,但为什么?

int c[5];
int* pc = c;
for (int i = 0; i < 5; i++)
{
    c[i] = i*2;
}
*pc++;
printf("%dn", pc-c );

有很多垃圾代码在运行。这是打印的唯一重要的事情:

int c[5];              // c is a pointer
int* pc = c;           // pc points to the same thing as c.
pc++;                  // pc now points to one-past-where-c-points-to
printf("%dn", pc-c ); // will print the pointer differences. 1.

注意

*pc++;

实际上意味着

*(pc++);

不同于

(*pc)++;

地址距离

似乎代码试图显示内存寻址空间中指针pcc的距离。

  1. int* pc = c;: pc指向c所指向的地方。(这里pc = c)

  2. *pc++;: pc增加1(此处为pc = c + 1)

  3. pc - c: pc - c = 1: 距离(它们之间的整数数)

,

 +------+------+------+------+------+
 |      |      |      |      |      |
 +------+------+------+------+------+
 ^      ^
 c      pc

您可以阅读定义良好的指针算术[expr]。

输出为1,因为它减去地址并返回差值