Return an Array in a Function

Hi guys,
Im making a function that finds the sum of two fractions(fractions are arrays of 2 elements). how would I return an array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int addFrac(int f1[2], int f2[2]){

int num1 = f1[0]; // numerator of fraction 1
int den1 = f1[1]; // denominator of fractions 1
int num2  = f2[0];//numerator of fraction 2
int den2 = f2[1];//denominator of fraction 2
int ans[2];//sim of fraction 1 and fraction 2.

if(den1 = den2) //if the two fractions have a common denominator.
    ans[0] = num1 + num2;//add the numerators
    ans[1] = den1;//keep the denominator.

return ans;//return the sum., but hiw?

}
Pass the array through to the function in the arguments list, you will also need to pass the size of the array through as a seperate item in the arguments list.

1
2
3
4
5
6
7
8
9
10
11
12
13
void foo(int array[], int size)
{
   for (int n = 0; n < size; ++n)
      array[n] = n*2;
}

int main() 
{
   int array[10];
   foo(array, sizeof(array)/sizeof(int));

   return 0;
}
Last edited on
A C-style array cannot be returned from a function. it can only be modified by reference or, as in ajh32's answer, through pointer to element.

You can return a C++ array (std::array<int, 2>) or a pair (std::pair<int, int>) or an object of any copyable or movable type you define -- you can even return a C-style array if it is a member of a class:
1
2
3
4
struct Fraction {
    int data[2];
};
Fraction addFrac(Fraction f1, Fraction f2);

Topic archived. No new replies allowed.