【问题标题】:Passing arrays to functions将数组传递给函数
【发布时间】:2012-10-03 04:47:25
【问题描述】:

我目前正在学习 C++ 入门课程,并且正在从事对数据进行排序的工作。我们最近介绍了结构,我决定使用结构来解决问题,而不是创建 3 个数组来保存数据文件中的信息。

我遇到的麻烦是当我试图将我的结构传递给我的函数时。 这是我的错误:

analyze_data.cpp: In function ‘int main()’:
analyze_data.cpp:76: error: conversion from ‘weather*’ to non-scalar type ‘weather’ requested
analyze_data.cpp: In function ‘int find_pos_of_smallest(weather, int, int)’:
analyze_data.cpp:110: error: no match for ‘operator[]’ in ‘data[pos]’
analyze_data.cpp:110: error: no match for ‘operator[]’ in ‘data[pos_of_smallest]’

我不明白第 76 行的错误。我对将结构传递给函数进行了一些研究,发现在类型声明中添加了“&”。但是,我不知道它的作用或为什么我需要这样做,因为我们没有在课堂上介绍它。我也试过了,但我得到了一组不同的错误。所以我想我不会发布这些,而是​​从我所知道的开始。

这是我的代码

  /*
    Program name: Analyze data
    Program discription:  This program will read a data file named data.txt.
      This data file is expected to be formated in a specific way and contain
      specific weather information.  The program will analyize this data and
      return max, min temperatures, 'perfect days', how many cold fronts per
      year, 10 coldest  and hottest days in a year and finally find the 5
      median days of the year.

    Date:  10/1/2012
  */

  #include <iostream>
  #include <fstream>

  using namespace std;

  /*
  * Declare struct's here
  *
  */ 
  struct weather
  {
    string date;
    int high;
    int low;
  };

  /* 
  *  Forward declaration of a function.  This declares the function,
  *  but does not define it.  (Notice that there is no code, just
  *  a function header with a semicolon after it.
  *
  */
  int find_pos_of_smallest (weather data, int start_pos, int end_pos);

  /* Our main function.
  *
  * Parameters:
  *    none
  *
  * Return value:
  *    0 if we complete successfully, 1 if there was an error.
  */
  int main()
  {
    //read the data file
    ifstream weather_data("data.txt");
    //declare array size, and then create array using struct
    int days = 365;
    weather data[days];

    //store the data.txt in the array and then close the file
    for (int i=0; i<days; i++)
    {
      weather_data >> data[i].date;
      weather_data >> data[i].high;
      weather_data >> data[i].low;
    }
    weather_data.close();

    ofstream data_results ("results.txt");
    // create the first 3 lines of the output reults in the following formated
    data_results << "Assignment #5\n"
                << "CS 1410/2000\n"
                << "Jonathan Larsen\n";
    /*
    for(int i=0; i<3; i++)
    {
      cout<<data[i].date << " "<<data[i].high << " " << data[i].low<<endl;
    }
    cout<<endl;
    */  
    cout<<find_pos_of_smallest(data, 0, days)<<endl;


    return 0;  //no error so return a zero  
  }//end of program


  /**** FUNCTIONS ****/

  /* Write down exactly what the function will do (a postcondition).
  * Write down what is required to use the function (any preconditions).
  * Write down any other behavior or comments that will help a programmer.
  *
  * Parameters:   (list parameters by type and name, and explain them)
  *   int example -- an example parameter
  *
  * Returns:
  *   double -- an example return value
  */

  /* Returns the position of the smallest value found in the specified
  * subarray.  (Only the elements in the subarray
  * between start_pos and end_pos inclusive are checked.)
  *
  * Parameters:
  *    d - a data array
  *    start_pos - the first position to check
  *    end_pos - the last position to check
  */
  int find_pos_of_smallest (weather data, int start_pos, int end_pos)
  {
    int pos_of_smallest = start_pos;

    for (int pos = start_pos+1; pos <= end_pos; pos++)
      if (data[pos].low < data[pos_of_smallest].low)
        pos_of_smallest = pos;

    return pos_of_smallest;
  }

【问题讨论】:

  • 您的函数采用weather 结构并将其视为数组。
  • 你需要在int find_pos_of_smallest (weather data, int start_pos, int end_pos);中传递一个指针而不是一个值,所以应该是:int find_pos_of_smallest (weather *data, int start_pos, int end_pos);
  • 只是一个建议:当发布这样的问题时,向我们显示相关行号所在位置的评论会有所帮助 - 幸运的是,在这种情况下它相当明显。
  • 另外,发布如下内容:pastebin.com/TGE39AL1 将帮助我们更快地找到问题。如果您可以将代码减少到可以证明您遇到的问题的最小数量,我们将不胜感激。
  • 好的,下次发帖时我会考虑到这一切。感谢您在提出建议的同时提供建设性的帮助。我只需要一个指针,不幸的是我们还没有了解它们是什么或它们是如何工作的。我现在担心的是,虽然我可能有一些我想象中的工作,但我可能不明白如何继续使用它来完成我的任务。再次感谢大家。

标签: c++ function struct structure


【解决方案1】:

您正在将一个数组传递给您的函数。您的函数需要采用weather[] 或weather* 类型。例如:

int find_pos_of_smallest (weather* data, int start_pos, int end_pos)

您应该注意,即使您传递的不是数组而是常规结构,您仍然应该通过引用传递。传递一个指针 (weather*) 并使用解引用成员运算符 (->) 或通过引用传递 (weather&) 并使用普通成员运算符 (.)。这是因为按值传递(没有 */&)会导致结构被复制到堆栈上的新值中,这对于大值(例如,如果字符串变大)可能需要相当长的时间。

【讨论】:

  • 很遗憾,我们还没有介绍如何通过指针或引用传递。然而,通过引用几乎似乎是我想要做的。那么我会做些什么来达到以下效果:int find_pos_of_smallest (weather &amp;data.low, int start_pos, int end_pos)?
  • 我的意思是说你想为天气结构创建一个打印功能。你会希望它是void print(weather&amp; day); 而不是void print(weather day);。对于数组,您需要使用 weather[] 或 weather*,它们都不会复制数据(它们将传递对现有数据的引用,在 C++ 中称为指针)。
  • 啊,明白了。谢谢你的澄清。我会投票给你,但我不能,因为我没有声誉。 ://
【解决方案2】:

您需要将数组作为指针传递:

int find_pos_of_smallest (weather *data, int start_pos, int end_pos)

将参数声明为weather data 意味着只是结构的一个实例。将其设为指针意味着您可以传递一个数组(该指针将获取数组中第一个元素的地址,当您使用data[pos] 对其进行索引时,您将获得该数组中的相关元素)。

【讨论】:

  • 啊,这可能是它不起作用的原因,我不知道如何尝试它,因为我们还没有学到任何关于指针的东西。我将在我的代码中尝试一下,如果它有效,我会将其标记为已回答并提前阅读有关指针的信息。
【解决方案3】:

每当你声明一个数组时,比如你的data 数组,在后续代码中单独写数组的名称(在本例中为data),令人困惑的是,实际上等同于写

&(data[0])

表示“data 数组的第一个元素的地址”。这就是数组通常“传递”到 C 和 C++ 中的函数的方式——通过传递它们的第一个元素的地址。这样做是因为在大型数组的情况下,传递其他类型参数的常用方法(即复制它们)会非常浪费。它还具有允许函数对数组所做的任何更改对调用代码可见的副作用(有时需要,有时不需要)。

您如何在函数中使用该地址?您使用指向weather 的指针:

int find_pos_of_smallest(weather* data, int start_pos, int end_pos)

指针是一个包含其他东西地址的变量。您可以使用* 间接运算符、-&gt; 运算符(如果指向的事物是struct 或class)访问指向的事物,以及方便地使用数组下标运算符[] :例如里面find_pos_of_smallest(),

data[5]

指的是weather元素数组中的第六个元素,从存储在指针data中的地址开始。

【讨论】:

    猜你喜欢
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2012-07-19
    • 2013-06-26
    相关资源
    最近更新 更多