c++代码输出说明

C++ Code Output explanation

本文关键字:说明 输出 代码 c++      更新时间:2023-10-16

我有以下代码,问题要求我找到输出。我通过输入找到了输出(2),但我很难弄清楚如何/为什么。任何帮助吗?

代码如下:

int scores[5];
int *numbers = scores;
for (int i=0; i <=4; i++)
  *(numbers+i)=i;
cout << numbers[2] <<endl;

你的代码实际上做了

scores[2] = 2;
cout<<scores[2]<<endl;

因此答案是…

详细说明:

int scores[5];
int *numbers = scores;  //numbers points to the memory location of the array scores
for (int i=0; i <=4; i++) // as mentioned, stray ';'
  *(numbers+i)=i; //same as numbers[i] = i  which is same as scores[i] = i
cout << numbers[2] <<endl;

for循环执行的唯一语句是

*(numbers+i)=i;

将使用差值操作符(*)存储int元素在该位置的索引。

然后打印出第三个数字,它等于2,因为数组从索引0开始。

设置指向数组的第一个内存位置的指针,然后遍历一系列内存地址并对其进行写操作。需要注意的是,使用带有解引用的指针算术

*(pointer + i) = i;

与使用下标操作符相同:

pointer[i] = i;