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; } 
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<long> another_vector; ...; another_vector = vectorName; Commented Apr 8, 2020 at 5: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? Commented Apr 8, 2020 at 5:29
  • Well do you want C++ vectors or not? Commented Apr 8, 2020 at 5:53
  • @BessieTheCow yes I do, as an alternative to the VLA. Commented Apr 8, 2020 at 6:10

1 Answer 1

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; } 
Sign up to request clarification or add additional context in comments.

4 Comments

hmm, then I will have a lot to change in my code, I'll try my best!
Also, by changing all of them to vectors, I can straight do another_p = p right?
@Kbklpl21 Yes, plain simple assignments between vectors is possible.
Ok I tried changing everything into vectors, and it failed miserably, the code stopped at p = generate_random_vector. Mind looking at the code? It's long though..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.