[英]I'm confused by this. Won't the array contents stay the same?
What will be the contents of the a array after the following statements are executed? 执行以下语句后,数组的内容是什么?
#include <stdio.h>
#define N 10
int main() {
int a[N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *p = &a[0], *q = &a[N - 1], temp;
while (p > q)
{
temp = *p;
*p++ = *q;
*q-- = temp;
}
printf("%d", a[N]);
return 0;
}
As stated in my comment nothing would happen, because p
is smaller than q
. 如我的评论所述,什么都不会发生,因为p
小于q
。
If you change your while loop to while (p <= q)
, you would inverse the order of the array. 如果将while循环更改为while (p <= q)
,则将颠倒数组的顺序。
You take the first element( p
) and put it in temp
. 您将第一个元素( p
)放在temp
。
Then you put the last element ( q
) and put it in the first place ( p
). 然后,您将最后一个元素( q
)放在首位( p
)。
Then you increment p
so it points to the second element. 然后增加p
,使其指向第二个元素。
Afterwards you write temp
in the last element. 然后,在最后一个元素中写入temp
。 And decrease q
so it points to the second to last element. 并减小q
,使其指向倒数第二个元素。 Do this again until p
is greater than or same as q
. 再次执行此操作,直到p
大于或等于q
为止。
edit: Your problem is with your print statement. 编辑:您的问题是您的打印语句。 You just print the element after the last element of the array by using a[N]
. 您只需使用a[N]
将元素打印在数组的最后一个元素之后。 Your array is from a[0]
to a[9]
. 您的数组是从a[0]
到a[9]
。 By reading from a[10]
you invoke undefined behavior, because it is not part of the array. 通过读取a[10]
您可以调用未定义的行为,因为它不是数组的一部分。 So you get a random number. 所以你得到一个随机数。
You'll want something like this. 您会想要这样的东西。
for (int i = 0; i<N;i++)
{
printf("a[%d] = %d\n",i,a[i]);
}
As Mak said, provided the while
condition is actually p < q
, the code switches the first and the last values, then the second and the second to last, etc. 如Mak所说,假设while
条件实际上是p < q
,则代码将第一个和最后一个值切换,然后将第二个和倒数第二个切换,依此类推。
Explanation 说明
The pointer p
is set at the beginning at the array, and q
, at the end. 指针p
设置在数组的开头, q
设置在结尾。 At every loop, the value at p
, which is *p
, is stored in temp
, then the value at q
, which is *q
, is put at p
, then p
is incremented (ie, it moves by one step towards the end of the array). 在每个循环中,将p
处的值*p
存储在temp
,然后将q
处的值*q
放入p
,然后p
递增(即,它向末尾移动一步)数组)。 Then, the value in temp
is put at q
, and q
is decremented (ie, it moves by one step towards the beginning of the array). 然后,将temp
的值放在q
,并将q
减1(即,它向数组的开头移动一步)。
When `p` and `q` meet, the loop breaks. 当“ p”和“ q”相遇时,循环中断。
Advice for the next time: print the array to know what it has become. 下一次建议:打印阵列以了解阵列的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.