Initialize vector of pointers to pointers

I have troubles initializing a vector of pointers to pointers (which I shouldn't do anyways I guess but please forgive me). I basically have a pointer z to a variable containing 0 and now I want to initialize a matrix that contains pointers to that pointer.

void example(int nrow, int ncol) {
    int zero = 0;
    int* z = &zero;
    int size = nrow * ncol;
    vector<int **> pointerMatrix(size);
    for (int i = 0; i < size; i++) {
        int** a = &z;       
        pointerMatrix.push_back(a);
    }
    //following line throws an exception:
    cout << **pointerMatrix[0] << endl;
}

Now the above code throws an exception, apparently there is nothing to be found under the address the pointer points to.

Anyone sees my mistake?

728x90

4 Answers Initialize vector of pointers to pointers

You allocate an array with the desired size, and then still use push_back to add further elements at the end.

Since you intend to fill the whole array with the same element, you should use this:

vector<int **> pointerMatrix(size, &z);

4 months ago

As described in the documentation pointerMatrix(size); creates a vector with having size amount of default-initialized (nullptr) elements, hence after the loop, your vector contains 2*size elements, having the first half filed in as nullptr, and the second half filed in as actual elements, hence cout << **pointerMatrix[0] << endl; tries to dereference a nullptr.

To fix this, you can, either, call reserve, to avoid unnecessary reallocations:

vector<int **> pointerMatrix;
pointerMatrix.reserve (size);

Or use operator[] to assign the values, instead of pushing them:

for (int i = 0; i < size; i++) {
    int** a = &z;       
    pointerMatrix[i] = a; // Or pointerMatrix[i] = &z;
}

4 months ago

push_back is used to add a new element past the end of the vector. It effectively increases the size of the vector to add the element at the end.

You already specified the size of your vector, so you can just access (and modify) the elements with operator[] for example:

for (int i = 0; i < size; i++) {
    pointerMatrix[i] = &z;
}

Alternatively, use a range-based for loop:

for (auto& entry : pointerMatrix) { // auto& can be replaced with int**&
    entry = &z;
}

4 months ago

vector<int **> pointerMatrix(size);

should be like

vector<int **> pointerMatrix;

Seems like there is a typo mistake in your implementation as pointer matrix seems already a size before the loop. you should either push a pointer value in index or dynamically push this. For this i guess, declaring vector pointerMatrix without defining size should works.

4 months ago