反转c中的数组 [英] Reverse an array in c
问题描述
我检查了一些用C语言反转数组的视频,因此我知道我的逻辑是正确的.这是我的代码:
I checked some videos of reversing an array in C therefore I know that my logic is correct. Here's my code:
#include <stdio.h>
void reverse( int arr[], unsigned int len )
{
int i=0;
int n=len;
int j=len-1;
int temp;
while (i<n)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
void reverse( int arr[], unsigned int len );
int main( void )
{
int a[] = {11, 19, 13};
unsigned int len = 3;
reverse( a, len );
int k=0;
for( k=0; k<len; k++ )
{
printf( "%d ", a[k] );
}
printf( "\n" );
return 0;
}
它输出相同的数组.我找不到问题所在.我应该为reverse
函数返回一些东西吗?
It outputs the same array. I couldn't find where the problem is. Should I return something for the reverse
function?
推荐答案
您将阵列反转了两次.这就是为什么您拥有原始数组.
You are reversing the array twice; that's why you have the original array.
如何?以一个10元素的数组为例.第一步,将交换第0个和第9个元素.最后一步,您将交换第9个和第0个元素.最终结果:没有变化.
How? Take for an example a 10-element array. As your first step, you'll swap 0th and 9th element. As your last step, you'll swap 9th and 0th element. Net result: no change.
您不想将i
最多运行到n
.您想将i
最多运行到j
,这样就永远不会将元素交换回来(即,将条件更改为while (i < j) { ... }
)
You don't want to run i
up to n
. You want to run i
up to j
, so that you never swap elements back (i.e. change the condition to while (i < j) { ... }
)
这篇关于反转c中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!