I have 2 functions (there are no differences between them, practically) Am I performing a return from them correctly? And how to properly call them in main (between arrays returned by both functions, you will need to perform mathematical operations)?

 int summa(int x[], int y[], int nRow) { int *sum = new int[nRow]; for (int i=0; i<nRow; i++) sum[i]=x[i]+y[i]; for (int i=0; i<nRow; i++) return sum[i]; } int dobutok(int x[], int y[], int nRow) { int *dob = new int[nRow]; for (int i=0; i<nRow; i++) dob[i]=x[i]*y[i]; for (int i=0; i<nRow; i++) return dob[i]; } 

    2 answers 2

    If you want to return sum[0] in the first case, and dob[0] in the second dob[0] , then this is correct.

    After the return is executed, the function stops working - so that of the entire cycle, the return will be executed only on the first iteration.

    But if you want to return the memory allocated for the new array, declare the function as returning an int* and simply return the return sum .

    Then do not forget to free the allocated memory.

     int * summa(int x[], int y[], int nRow) { int *sum = new int[nRow]; for (int i=0; i<nRow; i++) sum[i]=x[i]+y[i]; return sum; } int main() { int x[] = { 1, 2, 3}; int y[] = { 4, 5, 6}; int * s = summa(x,y,3); for(int i = 0; i < 3; ++i) cout << s[i] << endl; delete[] s; } 

    Like that.

    But where it is better to use, for example, vector - the probability of being mistaken is too high and forgetting to delete the returned array or to confuse its size ...

      Since you have already been answered, I will just add that it is easier and better to work in such cases with std :: valarray. He will do without function and unnecessary worries.

       int x[] = { 1, 2, 3}; int y[] = { 4, 5, 6}; std::valarray<int> vx(x, 3), vy(y, 3), result = vx + vy; for (int i : result) cout << i << endl; 
      • According to the condition of the problem: The product and the Sum of a pair (x [i] and y [i]) through f-th, and the difference between them is already in main =) So it happened. - Rinnekage