Crowe Crowe - 1 month ago 13
C Question

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;
}

Answer

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]);
}