okkvlt
- 53
- 0
in the c++ programming language, how do i make a function return an array?
This discussion focuses on returning arrays from functions in C++. It highlights that returning a local array directly is not feasible due to memory deallocation upon function termination. Instead, it recommends passing an array's pointer to the function or dynamically allocating memory using 'new'. Additionally, using C++ STL vectors is presented as a modern alternative for returning arrays, which simplifies memory management.
PREREQUISITESC++ developers, software engineers, and students learning about memory management and data structures in C++.
#include <iostream>
#include <cmath>
using namespace std;
double *roots (double *x, int n)
{
for (int k = 0; k < n; ++k)
x[k] = sqrt(k);
return x;
}
int main ()
{
double numbers[5];
double *sqrts;
sqrts = roots (numbers, 5);
for (int k = 0; k < 5; ++k)
cout << sqrts[k] << endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
void roots (double *x, int n)
{
for (int k = 0; k < n; ++k)
x[k] = sqrt(k);
}
int main ()
{
double numbers[5];
roots (numbers, 5);
for (int k = 0; k < 5; ++k)
cout << numbers[k] << endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
double *roots (int n)
{
double *x = new double[n];
for (int k = 0; k < n; ++k)
x[k] = sqrt(k);
return x;
}
int main ()
{
double *sqrts;
sqrts = roots (5);
for (int k = 0; k < 5; ++k)
cout << sqrts[k] << endl;
delete[] sqrts;
return 0;
}
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
vector<double> roots (int n)
{
vector<double> x(n);
for (int k = 0; k < n; ++k)
x[k] = sqrt(k);
return x;
}
int main ()
{
vector<double> sqrts;
sqrts = roots (5);
for (int k = 0; k < 5; ++k)
cout << sqrts[k] << endl;
return 0;
}