0

I have a function that puts a pointer into 10x10 std::array of pointers. I made a global vector that holds ints and have a function that creates new ints, puts them into vector and assigns their address in the grid. When I try to access grid, I get junk value even though all my values should be initialized.

I'm not sure where is my mistake. I checked the vector and all my created ships are there. Since my objects are still alive then I don't see why my pointer is not working.

#include <iostream>
#include <array>
#include <vector>

using namespace std;
using grid = array<array<int*, 10>, 10>;

vector<int> my_special_ints{};

grid fill_grid(int* val) {
    grid g;
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            g[i][j] = val;
        }
    }
    return g;
}

void modifying_function(grid& g) {
    for (int i = 0; i < 10; i++) {
        int temp_int = i + 10;
        my_special_ints.push_back(temp_int);
        g[i][0] = &my_special_ints.back();
    }
}

int main()
{
    int empty_int = -1;
    grid ptr_arr = fill_grid(&empty_int);

    modifying_function(ptr_arr);
    cout << *ptr_arr[1][0]; // junk value

}
3starblaze
  • 17
  • 4
  • 2
    Instead of saving a pointer to dynamically allocated memory, save the index. – stark Feb 19 '19 at 20:38
  • @user463035818 Made my example MVC and created less vague title accordingly to your request. – 3starblaze Feb 20 '19 at 18:46
  • you already got an answer and accepted it so I guess its fine, nevertheless it is good you added the mcve. sometimes, while creating a mcve you find the problem yourself, if not it is necessary for others to reproduce the exact same problem you have, also for future readers it makes it easier to see if their problem is the same or maybe something else – 463035818_is_not_an_ai Feb 20 '19 at 20:23

1 Answers1

3

When you call my_special_ints.push_back(temp_int);, the vector will allocate new memory if its capacity is full. This will invalidate all the pointers you created for your previous ints when this happens.

There are several possible solutions. One would be to reserve enough capacity (if you know how many ints you'll be adding before you start adding them).

Another solution would be to split modifying_function into two parts. First you'd add all the ints to the my_special_ints array. Then go thru that array and update your g grid.

3starblaze
  • 17
  • 4
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56