I am fairly new to C++ and have been avoiding pointers. From what I’ve read online I cannot return an array but I can return a pointer to it. I made a small code to test it and was wondering if this was the normal / correct way to do this:
#include <iostream>
using namespace std;
int* test (int in[5]) {
int* out = in;
return out;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int* pArr = test(arr);
for (int i = 0; i < 5; i++) cout<<pArr[i]<<endl;
cout<<endl;
return 0;
}
Edit: This seems to be no good. How should I rewrite it?
int* test (int a[5], int b[5]) {
int c[5];
for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
int* out = c;
return out;
}
Your code as it stands is correct but I am having a hard time figuring out how it could/would be used in a real world scenario. With that said, please be aware of a few caveats when returning pointers from functions:
int arr[5];, it’s allocated on the stack and is local to the function.arrtotest().std::unique_ptr/std::shared_ptr<>.Edit – to answer the use-case of matrix multiplication
You have two options. The naive way is to use
std::unique_ptr/std::shared_ptr<>. The Modern C++ way is to have aMatrixclass where you overloadoperator *and you absolutely must use the newrvalue referencesif you want to avoid copying the result of the multiplication to get it out of the function. In addition to having yourcopy constructor,operator =anddestructor, you also need to havemove constructorandmove assignment operator. Go through the questions and answers of this search to gain more insight on how to achieve this.Edit 2 – answer to appended question
If you are using this as
int *res = test(a,b);, then sometime later in your code, you should calldelete []resto free the memory allocated in thetest()function. You see now the problem is it is extremely hard to manually keep track of when to make the call todelete. Hence the approaches on how to deal with it where outlined in the answer.