首先是字符串的反转,关键要用两个位置来进行交换,i 从前往后,j 是从后往前,遍历一半,进行交换。
char * reverse_char(char *a)
{
int i =0,j;
char t;
cout<<"请输入字符串:"<<endl;
cin.getline(a,50,'\n');
for (i = 0,j = strlen(a)-1; i < (strlen(a)/2); i++,j--)
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
return a;
}
接下来是数组的反转,原理相似:
int *reverse_int(int *a)
{
int i = 0,j;
int length = sizeof(a)/sizeof(int);
for (i = 0, j=length -1 ; i < (length/2); i++,j--)
{
int temp = a[i];
a[i] = a[j];
a[j] =temp;
}
return a;
}
主函数测试用例:
void main()
{
char a[50];
memset(a,0,sizeof(a));
reverse_char(a);
for (int i = 0; i < sizeof(a); i++)
{
cout<<a[i]<<"";
}
cout<<endl;
int b[10] = {0,1,2,3,4,5,6,7,8,9};
reverse_int(b);
for (int i = 0; i < 10; i++)
{
cout<<b[i]<<" ";
}
cout<<endl;
}
运行结果: