Dynamic array of classes

Hi Folks,

I need a multidimensional array of a class which size and type is unknown at the beginning. I came up with the following idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
template <typename T> void initArray1D(T **array, int size1)
{
  array = (T**)malloc(size1*sizeof(T*));
  for (int i = 0; i < size1; i++) {
    array[i] = new T;
  }
}


int main(void)
{
  
  class anyClass {
    public:
    int x[150000];
  };
  
  anyClass **blub;
  initArray1D<anyClass>(blub,8);
  
  blub[5]->x[140000] = 3;
  cout << blub[5]->x[120] << endl;
  
  return 0;
  
}

This is the code for a 1D array which I used to examine the higher cases like 2D,3D etc which have been implemented straight forward.

However this code is crashing (it has not been that obvious until I created a class which needs much memory).
I cant figure out why and I'm interested in 2 things:
- What goes wrong?
- What is the proper way to do this?

Thanks in advance!
- What goes wrong?
blub is not changed.

- What is the proper way to do this?
1
2
3
  anyClass *blub = new anyClass[8];
  
  blub[5].x[140000] = 3;
See:
http://www.cplusplus.com/reference/new/operator%20new%5B%5D/
Last edited on
Topic archived. No new replies allowed.