pass arrays between functions

closed account (zT4NhbRD)
I just learned about arrays and am having trouble getting them to pass to another function.

I have an array that gets fill with randomly generated scores then I'm suppose to pass that array to a function that will print all those scores. However, all it's doing right now is saying the score number and actual score is 0 along with some weird negative number randomly inserted in the middle.

Last edited on
What does your main() do?
More to the point, what doesn't your 'main()' do?
closed account (zT4NhbRD)
The main is not supposed to do anything but execute the printStats function.

@TarikNeaj:
I watched the video but it doesn't help much. I can't specify what goes in the array. My problem is that once I fill the array in getScores, I need to pass it to printStats which is to print out the array but all I get is 0 and some random negative numbers.
The video shows exactly how to pass the array and print it out in a function. Your problem is somewhere else.

I'll take a closer look when I have more time, if no one else finds the time to help you.
Last edited on
You should call getScores() in your main();
once I fill the array in getScores

When is the getScores run? Who calls it?
closed account (zT4NhbRD)
getScores is runs as soon the program is compiled and runs.

No. When a program is run, only the main() is executed. When the main() ends, the whole program exits. Your main() calls printStat() and system(), but no other functions.

This is easy to test. Add a print command (like std::cout << "Hello\n";) into the getScores. Compile. Run.
closed account (zT4NhbRD)
It did print the statement but I see what you mean.
Last edited on
In other words your current code differs from the one you have posted initially.

Anyway, your main has two arrays. You do call printStat() with those arrays as parameters. You could call other suitable functions in the same way.
closed account (zT4NhbRD)
Here's the updated code:

Last edited on
The getScores() returns one double. That is why the line 16 is similar to:
double scores[N] = { 3.27 };

What does that do? It does create an array of N double elements and initializes the first element with value 3.27.
Additionally, the remaining N-1 elements are initialized with value 0.0.

Your getScores() does not use its parameter at all and does out-of-range dereferencing.

Your getScore() converts the integer that rand() returns into a double and then converts the double into int. Why?

Here is a main() for you:
1
2
3
4
5
6
7
int main() {
  constexpr int X = 100;
  double scores[X]; // uninitialized
  getScores( scores, X );
  printStat( scores, X );
  return 0;
}
Topic archived. No new replies allowed.