简体   繁体   中英

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 .

If you change your while loop to while (p <= q) , you would inverse the order of the array.

You take the first element( p ) and put it in temp .

Then you put the last element ( q ) and put it in the first place ( p ).

Then you increment p so it points to the second element.

Afterwards you write temp in the last element. And decrease q so it points to the second to last element. Do this again until p is greater than or same as 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] . Your array is from a[0] to a[9] . By reading from a[10] you invoke undefined behavior, because it is not part of the array. 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.

The pointer p is set at the beginning at the array, and q , at the end. 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). 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).

When `p` and `q` meet, the loop breaks.

Advice for the next time: print the array to know what it has become.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM