C++primer plus第六版课后编程题答案 7.7

7.7

//7.修改程序清单7.7中的3个数组处理函数,使之使用两个指针参数来表示区间.
//fill_array()函数不返回实际读取了多少个数字,而是返回一个指针,该指针
//指向最后被填充的位置;其他的函数可以将该指针作为第二个参数,以标识
//数据结尾。

#include <iostream>
using namespace std;

double *Fill_array(double *arr);////因为是对数组进行操作,所以可以不用返回值;
void const Show_array(const double *arr,double *Epoint);
void Reverse_array(double *arr,double *Epoint);
const int MAX=10;
void main77()
{
	double arr[MAX];
	double *end=Fill_array(arr);//使end指向最后一个指针
	Show_array(arr,end);
	Reverse_array(arr,end);
	system("pause");

}

double *Fill_array(double *arr) 
{
	double *p=arr;
	int i=0;//用于记录输入了多少个数字
	for(i=0;i<MAX;i++)
	{
		cout<<"
Please enter the "<<i+1<<" double values:";
		if((cin>>*(arr+i)))//如果输入非法值,跳出循环
		{
			p++;
			continue;
		}
		else
			break;
		
	}
	cout<<"
 you had input "<<i<<"  values!"<<endl;

	return p;
}

void const Show_array(const double *arr,double *end)
{
	const double *p=arr;
	cout<<"the array is:"<<endl;
	for(int i=0;i<MAX&&p<end;i++)
		cout<<*(p+i)<<"  ";
	cout<<"
show end!"<<endl;
}
void Reverse_array(double *arr,double *end)
{
	 double *p=arr;
	int temp;
	cout<<"
now Reverse the array!"<<endl;
	for(int i=1;i<(end-arr)/2&&p<end;i++)
	{
		temp=*(p+i);
		*(p+i)=*(end-i-1);
		*(end-i)=temp;
	}
	cout<<"this is the new array:"<<endl;
	Show_array(arr,end);
}

被这道题卡了好几天,因为不是很透彻地理解了关于函数指针的这一部分,只好上网找了下答案。

感谢http://blog.sina.com.cn/s/blog_4e6b6c2f01000a0c.html帖子对我的帮助。

原文地址:https://www.cnblogs.com/qq84435/p/3664884.html