Reputation: 187
I have a function that generates values in an array and returns a pointer to that array. Here's the MWE code:
int *f(size_t s)
{
int *ret=new int[s];
for(size_t a=0;a<s;a++)
{
ret[a]=a;
cout << ret[a] << endl;
}
return ret;
}
note that I have a cout
line in for for loop to prove to myself that the array is being populated properly.
Now, here's my problem. I can't find the correct method of using the returned array. Here's what I've been doing:
int main (void)
{
int ary_siz = 10;
int ary[ary_siz];
*ary = *f(ary_siz);
cout << ary[0] << endl;
cout << ary[2] << endl;
cout << ary[3] << endl;
}
The first element in ary
seems to be right. The others (ary[1]
,ary[2]
...) are not. Can anyone tell me what I'm doing wrong?
Upvotes: 0
Views: 76
Reputation: 10490
You allocate an array in the function and you just assign its first element to the first element of your stack-allocated array, instead of just using the returned array.
you should do something like that:
int main (void)
{
int ary_siz = 10;
int *ary;
ary = f(ary_siz);
cout << ary[0] << endl;
cout << ary[2] << endl;
cout << ary[3] << endl;
delete[] ary // don't forget to release the memory
return 0; // You should return something in the main function
}
Moreover, in C++ you should use vectors instead of "bare-metal" arrays whenever possible.
Upvotes: 1
Reputation:
How about this?
int *ary = f(ary_siz);
The you can just use the [] operator as you do in the couts.
Upvotes: 0
Reputation: 392999
The assignment
*ary = *f(ary_siz);
copies a single element. Use
int main (void)
{
int ary_siz = 10;
int *ary = f(ary_siz);
delete[] ary;
}
fixing the memory leak as well
Upvotes: 1
Reputation: 64308
int main (void)
{
int ary_siz = 10;
int *ary = f(ary_siz);
cout << ary[0] << endl;
cout << ary[2] << endl;
cout << ary[3] << endl;
delete [] ary;
}
Upvotes: 4