c++初学者一枚,希望有好心人能够帮我解答这行代码的意思

「已注销」 2015-06-13 09:10:31
该题为c++ primer plus 书籍中 第七章课后习题
这个double * fill_array(double *pfirst, double *pend)函数体中,
最后的return 返回了一个 --ptemp; 为什么要反回这个,这个位置有点看不懂,反回--ptemp是反回的什么东西?指针地址的自减吗?
另外: if (!cin) // bad input
{

cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
if(i == 0)
return ptemp;
else
return --ptemp;
}
这里也有 return --ptemp; 希望能有朋友帮我解答疑惑,感激不尽,为何要反回这个呢!
#include
const int Max = 5;
// function prototypes
double * fill_array(double *pfirst, double *pend);
void show_array( double *pfirst, double *pend);
void revalue(double *pfirst, double *pend, double r);
int main()
{
using namespace std;
double properties[Max];
double *pos = fill_array(properties, properties+(Max-1));
show_array(properties, properties+(Max-1));
cout << "Enter revaluation factor: ";
double factor;
cin >> factor;
revalue(properties, properties+(Max-1), factor);
show_array(properties, properties+(Max-1));
cout << "Done.\n";
return 0;
}
double * fill_array(double *pfirst, double *pend)
{
using namespace std;
double temp;
double * ptemp;
int i = 0;
for (ptemp = pfirst; ptemp <= pend; ptemp++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> temp;

if (!cin) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
if(i == 0)
return ptemp;
else
return --ptemp;
}
else if (temp < 0) // signal to terminate
break;
pfirst[i] = temp;
i++;
}
return --ptemp;
}
// the following function can use, but not alter,
// the array whose address is pfirst
void show_array( double *pfirst, double *pend)
{
using namespace std;
double * ptemp;
int i = 0;
for (ptemp = pfirst; ptemp <= pend; ptemp++,i++)
{
cout << "Property #" << (i + 1) << ": $";
cout << *ptemp << endl;
}
}
// multiplies each element of ptemp by r
void revalue(double *pfirst, double *pend, double r)
{
double *ptemp;
for (ptemp = pfirst; ptemp <= pend; ptemp++)
*ptemp *= r;
}
...全文
129 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zlmlczcmlvsaav 2015-06-13
  • 打赏
  • 举报
回复
double * fill_array(double *pfirst, double *pend); 这个函数的意思应该是填充数组并且返回数组最后一个值的指针吧。 for (ptemp = pfirst; ptemp <= pend; ptemp++) 这个for循环里面 ptemp跟pend做比较,从而控制循环退出。当ptemp等于了pend 再执行一次循环,ptemp就大于pend了,所以这个时候要得到数组的尾指针 ,就要用--ptemp, --放在变量前的意思是先对变量进行减操作,再使用减过后得到的值 问题还有,既然要得到尾指针,为什么不直接返回pend呢,因为代码里有这一段 else if (temp < 0) // signal to terminate break; 意思就是输入0 就停止填充数组,也就是说数组不一定被填充满了,函数只返回填充到那个数的指针。因为在这次循环里,ptemp已经被++了,只是输入的是0, 所以没有填充数字到这个指针指向的位置,所以这个不是数组的尾巴,还是要--ptemp 才指向数组的尾巴。 不知道解答了你的疑惑没有
king191923157 2015-06-13
  • 打赏
  • 举报
回复
for (ptemp = pfirst; ptemp <= pend; ptemp++) 因为有个 ptemp++,所以要减回去

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧