I am absolutely HORRIBLE at passing functions, and even more so with passing arrays. I'm trying to pass my "grades" array to the other functions, but I know I have to do it by reference since I can't return it. Can someone help shed some light?

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int readFile(int, int &count, int (&grades [10]));
int writeFile();
int averageGrades(int, int);

/**********************************************************************
* Reads an external file of grades and then returns those values to
* other functions in the program.
*********************************************************************/
int readFile(int sum, int &count, int (&grades [10]))
{
   //Declare variable
   char sourceFile[16];
   ifstream inStream;

   //Asking for user input
   cout << "Source file: ";
   cin >> sourceFile;

   //Open file
   inStream.open(sourceFile);
   if (inStream.fail())
   {
      cout << "Input file opening failed.\n";
      exit(1);
   }

   //Read from file and place in array
   for (int i = 0; i < 10 && inStream >> grades[i]; i++)
   {
      if (grades[i] == -1)
      {
         count++;
      }

      if (grades[i] != -1)
      {
         sum += grades[i];
      }
   }
   return sum;
}

/**********************************************************************
 * Reads an external file of grades and then returns those values to
 * other functions in the program.
 *********************************************************************/
int writeFile()
{
   ofstream outStream;
   char destinationFile[16];

   //Asking for user input
   cout << "Destination file: ";
   cin >> destinationFile;

   //Open file
   outStream.open(destinationFile);
   if (outStream.fail())
   {
      cout << "Output file opening failed.\n";
      exit(1);
   }

   outStream << grades[i];

   return 0;
}


/**********************************************************************
* Finds the average of the ten grades from the previous function.
***********************************************************************/
int averageGrades(int sum, int count, int average)
{
   //The magic formula to find the average
   if (count == 10)
   {
      cout << "Average Grade: ---%" << endl;
   }

   else
   {
      average = (sum / (10 - count));
      cout << "Average Grade: " << average << "%" << endl;
   }

   return average;
}


/**********************************************************************
* Basically a delegator. Calls other functions to do its dirty work.
***********************************************************************/
int main()
{
   //Declaring Variables
   int average = 0;
   int sum = 0;
   int count = 0;
   int grades[10];

   //Calling other functions
   sum = readFile(sum, count);
   average = averageGrades(sum, count, average);

   return 0;
}

Dani AI

Generated

Brief summary and concrete fixes for the posted code: the compile/run problems are not mysterious — the call sites and prototypes don’t match and a couple of functions try to use variables they never receive. Specifically, main() never passes grades to readFile, writeFile() has no parameters but attempts to use grades and i, and the filename buffer char[16] is brittle. and are correct that passing a pointer (array decay) will let a function modify the caller’s array; is also correct that you can pass a fixed-size C array by reference — but that form is brittle if the size ever changes.

A safer, clearer modern approach is to use a standard container and pass it by reference. Example pattern (uses std::vector so size is explicit and code is easier to reason about):

#include <vector>
#include <string>
#include <fstream>

int readFile(const std::string& filename, std::vector<int>& grades, int& missing)
{
    grades.clear();
    std::ifstream in(filename);
    if (!in) throw std::runtime_error("open failed");
    int x;
    while ((int)grades.size() < 10 && in >> x) grades.push_back(x);
    int sum = 0; missing = 0;
    for (int g : grades) if (g == -1) ++missing; else sum += g;
    return sum;
}

Use corresponding signatures for writeFile and averageGrades. For averaging, pass sum and the counts you already have; guard against division by zero (all grades missing). Replace raw char[] filenames with std::string. Keep responsibilities clear: one function reads and fills the container, another computes the average from the container and counters, another writes the container out.

Checklist to fix the original code: (1) make function prototypes and calls match (include the array/container parameter), (2) prefer std::vector or std::array over naked arrays, (3) check file open errors, (4) protect average computation when valid count is zero, and (5) avoid fixed-size filename buffers. This keeps intent clear and prevents the common bugs you have in the posted program.

Recommended Answers

All 5 Replies

Here's a simple way to pass an array.

#include <iostream>

void myfunc(int * x)
{
	for (int i = 0; i < 7; ++i)
		std::cout << x[i] << std::endl;
}

int main()
{
	int mya[] = {1, 2, 3, 4, 5, 6, 7};

	myfunc(mya);
	return 0;
}

To expand on what Gerard pointed out is when you pass an array to a function it actually only passes a pointer to the first element. Since you are working with pointers any change to a value in the array in a function is reflected in main.

void foo(int[]);
// or
void foo(int[SOME_NUMBER]);

// is the same as
void foo(int *);

I'm going to disagree with both gerard4143 and NathanOliver here. You can pass an array by reference as follows:

1) Change line 14 to the following:

int readFile(int sum, int &count, int (&grades) [10])

In case you're wondering what I changed, I moved one parenthesis.

2) Change line 107 to the following:

sum = readfile(sum, count, grades);

There may be other errors, but with a little luck, these suggestions will get you started in the right direction.

But there is no need for him to pass it by reference. I'm not saying you cant but asking why you would want to.

But there is no need for him to pass it by reference. I'm not saying you cant but asking why you would want to.

I have no idea :) Perhaps part of the original problem was to learn something about references.

I was just answering the question that was asked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.