Initializing array of pointers in C++

46,934

Solution 1

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
}

Solution 2

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.

Solution 3

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

Or, without dynamic memory allocaction :

int *array[10];
Share:
46,934
perkes456
Author by

perkes456

Updated on October 16, 2021

Comments

  • perkes456
    perkes456 over 2 years

    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?
    
    • perkes456
      perkes456 over 7 years
      What if the pointer is an object of another structure - ie. user defined structure... I'm guessing it's the same way?? @sorosh_sabz can you give an example?
    • juanchopanza
      juanchopanza over 7 years
      int * array[10] = {}; That initializes the pointers to nullptr.
    • Igor Tandetnik
      Igor Tandetnik over 7 years
      "how to initialize the array of pointers" That rather depends on what you want to initialize it to. What's the goal of the exercise?
    • perkes456
      perkes456 over 7 years
      @juanchopanza I wanna do it dynamically by using new operator.... Not statically...
    • Drew Delano
      Drew Delano over 7 years
      Probably the best thing to do is not use an array or pointers if you can help it. What problem are you trying to solve?
    • juanchopanza
      juanchopanza over 7 years
      @perkes456 Well you can't because you have an array of length 10.
    • songyuanyao
      songyuanyao over 7 years
      You might want int * array[10] = {new int, new int, ...}; ?
    • Jarod42
      Jarod42 over 7 years
      auto myarray = std::make_unique<int*[]>(10); ?
    • perkes456
      perkes456 over 7 years
      @juanchopanza So I'm not gonna use the new operator with this one... ?
    • juanchopanza
      juanchopanza over 7 years
      @perkes456 I can't see why you'd want to do that, but maybe you could clarify your question.
    • Jean-François Fabre
      Jean-François Fabre over 7 years
      @songyuanyao int * array[10] = {new int, new int, ...};: how much C++ has changed while I was away on mars?
    • molbdnilo
      molbdnilo over 7 years
      You initialise it like any array, int* array[10] = { item_0, item_1, item_2, and so on. Elements left out are initialised to null. array = new int[10]; is nonsense because array is not a pointer.
    • songyuanyao
      songyuanyao over 7 years
      @Jean-FrançoisFabre It's aggregate initialization, from C++98 (?)
    • Jean-François Fabre
      Jean-François Fabre over 7 years
      Thank you. I'll try to use latest C++ 11 standards from now on. My C++ coding standards need dusting. And there's everything you need in SO.
  • perkes456
    perkes456 over 7 years
    This isn't it either... Can someone just tell me if I'm supposed to use operator "NEW" with array of pointers when initializing it... gosh lol
  • C. Flint
    C. Flint over 7 years
    if you don't want dynamic allocation : int *array[50];
  • juanchopanza
    juanchopanza over 7 years
    You don't need a loop to initialize the elements to NULL. See my first comment. i.e. what you're showing is far from the best practice.
  • Garrigan Stafford
    Garrigan Stafford over 7 years
    the new operator is specifically for dynamically allocating memory off the heap, it isn't statically allocated by the compiler, so using new is a huge difference from the regular way other than you have to specifically delete the memory
  • Garrigan Stafford
    Garrigan Stafford over 7 years
    Depends on the compiler, older ones like gcc don't have default values for primitives, which usuaslly means what ever fragmented bits were still alive in memory when it was allocated will still be there and the starting value of the variable
  • juanchopanza
    juanchopanza over 7 years
    As per my comment to OP, int * array[10] = {}; Done. No need for loops.
  • perkes456
    perkes456 over 7 years
    This pretty much covers the whole thing that I needed! Thanks!
  • Galik
    Galik over 7 years
    @perkes456 This is the answer. You are doing two different things in your question. One is an array of pointers on the stack and the other is a dynamic array of pointers on the heap. This answer gives you both methods, pick the one you want.
  • Holt
    Holt over 7 years
    Even better, use std::array for the static part, e.g. std::array<std::vector<int>, 10>.
  • Jean-François Fabre
    Jean-François Fabre over 7 years
    upvoting because & answers the question partially.
  • Jean-François Fabre
    Jean-François Fabre over 7 years
    Didn't know that. Nice one. But the OP wanted it to be dynamic. I'll keep that in mind.
  • juanchopanza
    juanchopanza over 7 years
    @Jean-FrançoisFabre except for the missing initialization of the array of pointers?
  • Zeokav
    Zeokav over 7 years
    I thought he just wanted the declaration syntax. But anyway, int **array = new int*[n](); This initializes the array as well.
  • Jean-François Fabre
    Jean-François Fabre over 7 years
    it was ambiguous whether he wanted to initialize the arrays or not. But, I agree, this was the next step. I always try to go deeper in basic questions like this otherwise all answers are the same, so I covered that part too.
  • juanchopanza
    juanchopanza over 7 years
    @Jean-FrançoisFabre Silly me, I must have been confused by the title and "I forgot how to initialize the array of pointers in c++..."
  • perkes456
    perkes456 over 7 years
    I must've clicked on it accidentally, it's there now :)