传入一个数组,和数组长度,但是我写这个函数,为什么没有作用呢?


void fun(int* a,int n)
{
    int* x = a+n-1; 
    int t,i=0;
    int* j = a;
    while ( i <=(n-1)/2 )
    {
        t = *x;
        *x = *j;
        *j = t;
        x--;
        j++;
        i++;
    }
    
}

看了半天没看出毛病,求解

你的函数没有问题哦,测试代码:

#include <stdio.h>
int main()
{
    int a[]={1,2,3,4,5};
    fun(a, 5);
    for(int i=0;i<5;i++)
        printf("%d ", a[i]);
    return(0);
}

输出:
5 4 3 2 1

img

我用你的代码是正确的,看一下你的调用是不是错了。

#include <stdio.h>
 
void fun(int* a,int n)
{
    int* x = a+n-1; 
    int t,i=0;
    int* j = a;
    while ( i <=(n-1)/2 )
    {
        t = *x;
        *x = *j;
        *j = t;
        x--;
        j++;
        i++;
    }
    
}
int main()
{
   /* 我的第一个 C 程序 */
    int a[6]={2,5,3,6,4,7};
    fun(a,6);
    for(int i=0;i<6;i++)
   printf("%d \n",a[i]);
   
   return 0;
}