[英]Need help understanding output of a pointer exercise
Hi i'm studying a book and there is a question that displays this code: 嗨,我正在读书,有一个问题显示此代码:
What is the output of the following code? 以下代码的输出是什么?
int main()
{
int x;
int *p;
int *q;
p = new int[10];
q = p;
*p = 4;
for(int j = 0; j<10; j++)
{
x = *p;
p++;
*p = x+j;
}
for(int k= 0; k<10; k++)
{
cout << *q << " ";
q++;
}
cout << endl;
return 0;
}
I know the output is: 我知道输出是:
4 4 5 7 10 14 19 25 32 40 4 4 5 7 10 14 19 25 32 40
but i cannot understand why, i know p = q and since the first p in the array of 10 equals 4 so does q but after that shouldnt it just increment by one each time since j is? 但是我不明白为什么,我知道p = q,由于10的数组中的第一个p等于4,所以q也是如此,但是在那之后它不应该每次递增1,因为j是?
p++
increment the pointer so it points to the next element. p++
递增指针,使其指向下一个元素。 This is known as pointer arithmetic. 这称为指针算术。 This is not affecting the value. 这不会影响价值。 For that, you need to dereference the pointer using *
as in *p = x+j
为此,您需要使用*
取消引用指针,如*p = x+j
*p = x+j;
sets the value pointed to by p
to x+j
. 将p
指向的值设置为x+j
。 x
= value pointed to previous p
(before increment) and j
goes from 0 to 9. So it gives: x
=指向前一个p
(在增量之前)的值,并且j
从0到9。所以它给出:
4+0(4), 4+1(5), 5+2(7), 7+3(10), ... 4 + 0(4),4 + 1(5),5 + 2(7),7 + 3(10),...
Since it initialize first element to 4 and start writing at second element, that is why you have two 4s at the beginning. 由于它将第一个元素初始化为4并从第二个元素开始写入,因此这就是为什么您在开头有两个4的原因。
However, I think the loop should be 但是,我认为循环应该是
for(int j = 0; j<9; j++)
{
x = *p;
p++;
*p = x+j;
}
else there will be out of bound access to p
. 否则将无法访问p
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.