1

I have an array of pointers to vectors vector<int> *F[12]; and I wish to initialize some vectors and store their addresses in F.

for(uint i = A; i <= B; ++i){
    vector<uint> newvec(pow2(i), 0);
    F[i] = &newvec;
}

But when I try to access them later, I find that they are not all zero:

for(uint i = A; i <= B; ++i){
    for(uint j = 0; j <= pow2(i); ++j){
        if((*F[i]).at(j) != 0){
            cout << i << "/" << j << "/" << (*F[i]).at(j) << "|";
        }
    }
}

I assume this has something to do with the scope of the declared vector. Why has the memory been freed? Do I have to use malloc and create a vector from that?

jcai
  • 3,448
  • 3
  • 21
  • 36
  • 1
    http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris Oct 07 '12 at 03:12

2 Answers2

2

newvec goes out of scope when the loop exits. Any existing reference or pointer to it is invalid at that point. You'll need to declare the object at the appropriate scope (I don't know what that is for you in this case, but certainly outside the for loop).

Ed S.
  • 122,712
  • 22
  • 185
  • 265
2

newvec is being created on the call stack each iteration. Each time through the loop you create it, make a pointer to it, then it vanishes. You want to use the 'new' operator to create a longer-lasting instance of the vector in the heap.

DarenW
  • 16,549
  • 7
  • 63
  • 102
  • `vector * newvec = new vector(pow2(i), 0); F[i] = newvec;` seems to fix it, thanks. – jcai Oct 07 '12 at 03:51
  • @user49164: There's no reason to dynamically allocate the vector here. One of the benefits of working with a container like `std::vector` is that it manages memory for you. When you allocate it dynamically you now have to deallocate it. Best to just tale a `vector&` as an argument to the function and fill it or return a `vector` – Ed S. Oct 07 '12 at 17:53