Hi , everyone !
how to return an array from a function ?
just like this code ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include<iostream>
using namespace std;
int factors(int x)
{
int arr[1000];
for(int i=1;i<=x;i++)
{
if(x%i==0)
arr[i]=x/i;
}
return arr;
}
int main()
{
int x=60;
factors(x);
}
|
Last edited on
No.
Line 5: arr is a local variable. It goes out of scope when factors() exits, therefore the memory occuped by arr is no longer valid.
Line 4: You're declaring that factors() returns an int, not a pointer.
Line 16: Even if the memory returned by factors() was valid, you're ignoring the pointer returned by factors().
You have a couple of options:
1) Pass the array as an argument when calling factors().
2) Allocate the array dynamically.