【问题标题】:For loop using pointers to traverse array not working properly使用指针遍历数组的 For 循环无法正常工作
【发布时间】:2019-09-18 17:00:25
【问题描述】:

对于我的作业问题,我必须使用指针来遍历数组。当我尝试将 3 个“名称”值存储到名为 RentalAgencyObject 数组的成员变量中时,我发现它存储了值,但从不增加。因此,给定的最后一个值存储在第一个索引中,接下来的两个为空。

RentalAgency *agencies_ptr = agencies;

for(int i = 0; i < 3;i++,++agencies_ptr){
    infile.get((agencies->name),MAX_SIZE,space);
}

agencies 是一个对象数组

如果输入是 Hertz、Alamo 和 Budget,它应该输出 Hertz、Alamo 和 Budget。 实际输出只是预算。

【问题讨论】:

  • 可能是错字?你需要infile.get((agencies_ptr-&gt;name), MAX_SIZE, space);
  • agencies 是什么?没有看到agencies,我们怎么知道++agencies_ptr是否有意义?
  • 啊,是的,你是对的,我是新手,不明白。谢谢@RSahu

标签: c++ arrays loops pointers


【解决方案1】:

随便写

for(int i = 0; i < 3; i++){
    infile.get( agencies_ptr[i].name, MAX_SIZE, space );
}

【讨论】:

    【解决方案2】:

    您正在取消引用 agencies,而不是 agencies_ptr(并且不需要括号):

    RentalAgency *agencies_ptr = agencies;
    
    for(int i = 0; i < 3; ++i, ++agencies_ptr)
       infile.get(agencies_ptr->name, MAX_SIZE, space);
    

    但一种更惯用的遍历“范围”的方式是这样的(it 代表iterator):

    RentalAgency *agencies_it = agencies;
    RentalAgency *agencies_end = agencies_it + 3;
    
    for(; agencies_it != agencies_end; ++agencies_it)
       infile.get(agencies_it->name, MAX_SIZE, space);
    

    它更简洁,更能表达意图,并且在有经验的程序员中更常见。

    【讨论】:

      猜你喜欢
      • 2013-05-20
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多