Search code examples
c++classmultidimensional-arrayallocation

c++ array[var][2] as a class member


I would like to have an array of unsigned integers within a class, and its size should be [var][2], so the user will be able to choose var in runtime. Is there a better way than allocating a two dimensional array (an allocated array of pointers to allocated arrays)?

In the class I have:

unsigned int *(*hashFunc); 

And in the initializing function:

hashFunc = new unsigned int*[var];
for(unsigned int i = 0; i<var; ++i)
    hashFunc[i] = new unsigned int[2];

I want to only allocate once, and I think it should somehow be possible because I only have one unknown dimension (var is unknown but 2 I know from the beginning).

Thanks!


Solution

  • (To answer the direct question.) You can declare the pointer as

    int (*hashFunc)[2];
    

    and allocate it in one shot as

    hashFunc = new int[var][2];