Small problem: store a set of numbers in reverse order

Do the question, given an array, store the elements in reverse order.

This question is simple to say, it can be written with pointers, or it can be implemented with array subscripts. But something went wrong when I implemented it with pointers

Here is the code for pointer mode:

#include<stdio.h>
#define N 5
int main()
{
    int i,*temp;
    int ar[N] = {8,4,5,3,1};
    int *x = ar;
    int *y = &ar[N-1];
    while(x<y)
    {
        *temp = *x;
        *x = *y;
        *y = *temp;
        x++;
        y--;
    }
    for(i=0;i<N;i++)
    printf("%d",ar[i]);

}

Have you, see what's wrong?

For beginners like me, this problem may be a more difficult problem. When we compile this code, the system will not prompt an error.

But there is a problem when running it.

Why is this? Have you noticed that when I define this *temp pointer, it is not initialized, and in c language, the uninitialized pointer

It will be pointed to the kernel area by default by the system. The kernel area is an area that the user cannot access, so an error will occur when performing the swap.

Here we just need to point it to the address of a variable (ie initialize it).

The following is the code using the subscript method, it is recommended for beginners to use it, and it is easy to check errors:

/*#include<stdio.h>
#define N 5
int main()
{
    int i = 0,j = N-1,temp;
    int ar[N] = {8,4,5,3,1};
    int x = ar[0];
    int y = ar[N-1];
    while(i<j)
    {
        temp = ar[j];
        ar[j] = ar[i];
        ar[i] = temp;
        i++;
        j--;
    }
    for(i=0;i<N;i++)
    printf("%d  ",ar[i]);
}*/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324846559&siteId=291194637