Hy, I would like to return dynamic array, but I get error with my code and can't seem to find tutorial online with this. Can anyone pleas help me with this?
Line 16 creates an empty vector. Line 5 creates another empty vector inside the function. Line 8 is trying to access an individual element of an empty vector, so it has no place to store "index".
Although a vector is like an array where you can use a subscript to access a populated vector, the subscript will not work to add to the vector. What you need to use to add to a vector is "myarray.emplace_back" or ".push_back" to load the array.
That said I need to load this program into my IDE and see what is not working.
In your function test, you create a vector of size zero. Then, you try to populate it. You try writing into the first element of the vector, which doesn't exist.
This is bad.
Your choices are:
1) Make the vector big enough (either at construction time, or using resize) so you don't write into elements that don't exist.
2) Use push_back to add to the end of the vector; this will resize it as needed.
#include <iostream>
usingnamespace std;
int *test( int i )
{
int *myarray = newint[i];
for ( int index = 1; index <= i; index++ ) myarray[index-1] = index;
return myarray;
}
int main()
{
int *v = test( 5 );
for ( int a = 0; a < 5; a++ ) cout << v[a] << '\n';
delete [] v;
}