1

Dynamic array in Stack? So from this link, I saw this:

#include <iostream>
#include <vector>

int main()
{
    int x = 0;
    std::cin >> x;

    std::vector<char> pz(x);
}

But what I want is something like this:

include <iostream>
include <vector>

using namespace std;

int main()
{
     long int *p;
     long int *another_p;
     p = generate_random_vector(); //this is a function that generates a vector
                                   //and I'm assigning this vector to *p

     vector<long int>vectorName(n); //size n will be known when I read from a file
                                    //I would like to store the value of vector of *p in vectorName

     *another_p = vectorName; //I would like to store the value of vectorName in *another_p

     return 0;
}

So any suggestions on doing this?

Here's what I originally did which isn't allowed in C++:

int main()
{
     long int *p;
     long int *another_p;
     long int arrayName[n]; //n can be obtained from reading a file

     p = generate_random_vector(); 

     for ( int i = 0; i < n; i++ )
     {
          arrayName[i] = p[i];
     }

     for ( int i = 0; i < n; i++ )
     {
          another_p[i] = arrayName[i];
     }
     return 0;
}
Kbklpl21
  • 11
  • 4
  • First of all, when you say "vector" you should actually *use* a vector, not pointers. Secondly, if you have two real vectors (`std::vector`) then to copy from one to the other you can use simple and plain assignment: `std::vector another_vector; ...; another_vector = vectorName;` – Some programmer dude Apr 08 '20 at 05:26
  • @Someprogrammerdude I'm calling it vector because mathematically it is a vector, and the code I'm trying to do is mathematics, maybe I should call it array instead? – Kbklpl21 Apr 08 '20 at 05:29
  • Well do you want C++ vectors or not? – eesiraed Apr 08 '20 at 05:53
  • @BessieTheCow yes I do, as an alternative to the VLA. – Kbklpl21 Apr 08 '20 at 06:10

1 Answers1

2

If you modify generate_random_vector to return an std::vector<long int>, and define another_p and arrayName as std::vector<long int> as well (default constructed, no need to specify size) then you can simply use assignment , as I said in my comment:

std::vector<long> generate_random_vector();

int main()
{
     std::vector<long> p;
     std::vector<long> another_p;
     std::vector<long> arrayName;

     p = generate_random_vector(); 

     arrayName = p;
     another_p = arrayName;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621