Returning arrays from a function

  • Thread starter Thread starter sdoug041
  • Start date Start date
  • Tags Tags
    Arrays Function
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
sdoug041
Messages
25
Reaction score
0
hello. I am working on a c++ assignment right now, and my job is to write a sub-program that will fill two arrays with random numbers (1-10), then ask the student 10 arithmetic questions (either multiply or divide depending on a previous choice) and store the answers in a third arrray. I come across problems when trying to call the function and returning the array from the function. (the answers)

in the main () i have something like

int student_answers [10];
student_answers [10] = run_test ();

the above 3 lines are an attempt to call the function but I have limited knowledge about arrays.

in the sub-program itself I have something like:

int run_test (int verification)
... bunch of code... stores answers in answer[10]
return (answers[10]);

is ths the correct way of returning an array?
 
Last edited:
Physics news on Phys.org
No. A C/C++ function can't return an entire array. It can return a pointer to an array, or the address of an existing array can be passed as a parameter to the function, and when the function exits, the array will have its values filled in. (BTW, the term subprogram is not usually used in C/C++; the term most often used is function.)

Look at your text and/or notes to see how arrays are passed as parameters in functions.

sdoug041 said:
in the sub-program itself I have something like:

int run_test (int verification)
... bunch of code... stores answers in answer[10]
return (answers[10]);
There are several errors in the function skeleton above.
  1. run_test returns an int, a single integer value. Your intent was to return an entire array (which you can't do), so there is a mismatch between what your function returns and what your previous statement intends to do.
    Code:
    student_answers [10] = run_test ();
  2. In the call to run_test just above, there are no parameters, but in your function definition, there is an int parameter, verification.
  3. Where you said "stores answers in answer[10]" there are two problems: For an array with 10 elements, the last element is answer[9], not answer[10]. Also, you are apparently trying to put all your answers in one element of your array, not in answer[0], answer[1], ..., answer[9].
  4. Your return statement attempts to return a single value in your array, answer[10]. As already noted, this is not an element in your array. Furthermore, it is not an array: it is a single integer value.