/*
* Copyright (c) 2012, 烟台大学计算机学院
* All rights reserved.
* 作 者:解晓东
* 完成日期:2012 年 12 月 6 日
* 版 本 号:v1.0
*
* 输入描述:
* 问题描述:用指针实现逆序存放数组元素
* 程序输出:
* 问题分析:
* 算法设计:
*/
#include <iostream>
using namespace std;
int inverte(int *x, int n); /*函数声明*/
int main()
{
int i, a[10]=
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 0
}; /*定义数组*/
puts("The elements of original array:\n");
for (i=0; i<10; ++i) /*输出数组*/
cout << a[i] << " ";
cout << endl;
inverte(a, 10); /*使数组元素逆序*/
puts("The elements has been inverted:\n");
for (i=0; i<10; ++i) /*输出逆序后的数组*/
cout << a[i] << " ";
cout << endl;
return 0;
}
int inverte(int *x, int n)
{
int *p, temp, *i, *j, m = (n-1)/2; /*声明变量*/
i = x; /*变量i存放数组首地址*/
j = x + n - 1; /*变量j存放数组末尾元素地址*/
p = x + m; /*变量p存放数组中间元素地址*/
for (; i<=p; ++i, --j) /*交换数组前半部分和后半部分元素*/
{
temp = *i;
*i = *j;
*j = temp;
}
return 0;
}
/*
*在VC++6.0中运行的结果是:
*-----------------------------
*The elements of original array:
*
*1 2 3 4 5 6 7 8 9 0
*The elements has been inverted:
*
*0 9 8 7 6 5 4 3 2 1
*Press any key to continue
*-----------------------------
*/
用指针实现逆序存放数组元素
最新推荐文章于 2023-10-17 23:11:52 发布