An array decays into a pointer to its 1st element. You are returning a pointer to an element of a local array that gets destroyed when it goes out of scope at function exit, thus the caller ends up with a dangling pointer to invalid memory.
To solve this, you have several options:
You can let the caller allocate the array first, and then pass it by pointer/reference into the function to fill it in:
#include <iostream>
using namespace std;
void AddData(int (&factors)[10]) {
// or: void AddData(int *factors) {
for (int start = 0; start < 10; start++) {
factors[start] = start + 1;
}
}
void main() {
int factors[10];
AddData(factors);
for (int i = 0; i < 10; i++) {
cout << factors[i] << "\n";
}
}
Or, you can let the function allocate the array dynamically so it is not destroyed until the caller is done using it:
#include <iostream>
using namespace std;
int* AddData() {
int *factors = new int[10];
for (int start = 0; start < 10; start++) {
factors[start] = start + 1;
}
return factors;
}
void main() {
int *factors = AddData();
for (int i = 0; i < 10; i++) {
cout << factors[i] << "\n";
}
delete[] factors;
}
In which case, you should return the array as a std::vector
instead, and let it manage the dynamic memory for you:
#include <iostream>
#include <vector>
using namespace std;
vector<int> AddData() {
vector<int> factors(10);
for (int start = 0; start < 10; start++) {
factors[start] = start + 1;
}
return factors;
}
void main() {
vector<int> factors = AddData();
for (int i = 0; i < 10; i++) {
cout << factors[i] << "\n";
}
}
Or, since the number of array elements is fixed at compile-time in your example, you can use std::array
instead:
#include <iostream>
#include <array>
using namespace std;
array<int,10> AddData() {
array<int,10> factors;
for (int start = 0; start < 10; start++) {
factors[start] = start + 1;
}
return factors;
}
void main() {
array<int,10> factors = AddData();
for (int i = 0; i < 10; i++) {
cout << factors[i] << "\n";
}
}