perkes456 perkes456 - 1 year ago 74
C++ Question

Initializing array of pointers in c++

I forgot how to initialize the array of pointers in c++ like following:

int * array[10];

Is this a proper solution like this? Here:

array = new int[10];

// is this the correct way??

Answer Source
int * array[10];

defines 10 pointers on 10 int arrays statically

To go dynamic:

int **array = new int *[10];

Better solution since you use C++: use std::vector

std::vector<int *> v;
v[2] = new int[50];  // allocate one array

Since we're using vectors for the array of pointers, lets get rid of the pointers completelely

std::vector<std:vector<int> > v;
v[2].resize(50);  // allocate one array

Then access the array like a matrix:

v[3][40] = 14;

Going further, one way to initialize all the rows, using C++11, making a 10x50 int matrix in the end (but size can also change within the loop if we want). Needs gcc 4.9 and g++ -std=c++11 to build

std::vector<std::vector<int> > v;
for (auto &it : v)
   it.resize(50);  // allocate arrays of 50 ints
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download