Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing array of pointers in C++

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

int * array[10];

Is this a proper solution like this? Here:

array = new int[10];

 // Is this the correct way?
like image 988
perkes456 Avatar asked Aug 12 '16 13:08

perkes456


2 Answers

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.resize(10);
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.resize(10);
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;
v.resize(10);
for (auto &it : v)
{
   it.resize(50);  // allocate arrays of 50 ints
}
like image 155
Jean-François Fabre Avatar answered Oct 02 '22 01:10

Jean-François Fabre


In general in most cases there is no great sense to initialize the array with exact addresses. You could assign the addresses or allocate appropriate memory during the usage of the array.

Usually there is sense to initialize an array of pointers with null pointers. For example

int * array[10] = {};

If you want to declare the array and at once to allocate memory for each element of the array you could write for example

int * array[10] = 
{ 
    new int, new int, new int, new int, new int, new int, new int, new int, new int, new int 
}; 

or

int * array[10] = 
{ 
    new int( 0 ), new int( 1 ), new int( 2 ), new int( 3 ), new int( 4 ), new int( 5 ), new int( 6 ), new int( 7 ), new int( 8 ), new int( 9 ) 
}; 

But in any case it would be better to do the assignment using some loop or standard algorithm because in general the array can have more than 10 elements.

Also you should not forget to delete all allocated memory. For example

std::for_each( std::begin( array ), std::end(array ), std::default_delete<int>() );

Or if you have already defined objects of type int you could write for example

int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9;
//...
int * array[10] = 
{ 
    &x0, &x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9 
}; 

Such an initialization is used very often for arrays of function pointers.

like image 39
Vlad from Moscow Avatar answered Oct 02 '22 01:10

Vlad from Moscow