Return array

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>

std::vector<int> test(int i) {
    std::vector<int> myarray;
    for (int index = 1; index <= i; i++)
    {
        myarray[index] = index;
    }
    return myarray;
}

int main()
{
    std::vector<int> v = test(5);
    for(int a = 0; a < 5; a++)
    {
        std::cout << v[a] << "\n";
    }

    return 0;
}
Hello spartannn,

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.

Hope that helps for now,

Andy
That's not a dynamic array. It's a vector.

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.
Hello spartannn,

After working with the program I found the simple mistake:

for (int index = 1; index <= i; i++)

should be:

for (int index = 1; index <= i; index++)

Along with my previous post using "emplace_back" with the vector it works.

Hope that helps,

Andy
"Dynamic array" or "vector"?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int *test( int i )
{
   int *myarray = new int[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;
}
Registered users can post here. Sign in or register to post.