Reputation: 121
#include <iostream>
#include <vector>
void init()
{
std::vector<double> b;
b.push_back(10);
return;
}
double mean(double *array, size_t n)
{
double m=0;
for(size_t i=0; i<n; ++i)
{
m += array[i];
}
std::cout<<*array<<std::endl;
return m/n;
}
int test(int *b)
{
int dist;
dist=b[0];
return dist;
}
int main()
{
int x=0;
int y=0;
//double a[5]={1, 2, 3, 4, 5};
std::vector<double> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
std::cout<<mean(&a[0], 5)<<std::endl; // will print 3
init();
y=test(&b[0]);
std::cout<<y<<std::endl;
return 0;
}
I am trying to check if I can initialize vector "b" in "init" function and retrieve value in "test" function to finally return as "y" in main function. Is this even possible? It is just a test code to explore this possibility.
Upvotes: 1
Views: 77
Reputation: 141658
Maybe you want:
std::vector<double> init()
{
std::vector<double> b;
b.push_back(10);
return b;
}
and then in main:
auto b = init();
y = test( &b.at(0) );
When calling mean
. get the size as a.size()
instead of hardcoding the 5. And pass a.data()
instead of &a[0]
, then it won't crash if the vector is empty.
Upvotes: 2