Search code examples
c++arraysmemoryfixed

Creating a dynamic sized array of fixed sized int arrays in C++


For some reason this is giving me more trouble than i thought...

int *myArray[3];

myArray = new int[mySize];

does not work...

I've used a typedef before in a similar manner and it worked perfectly, but this time i dont want to create the typedef


Solution

  • One might be tempted to do this:

    ::std::vector<int[3]> myArray;
    

    Because vector is so nice for dynamically sized arrays. Unfortunately, while that declaration works, the resulting vector is unusable.

    This will be just as efficient, if you have ::std::array (a C++11 feature) and it will actually work:

    ::std::vector< ::std::array<int, 3> > myArray;
    

    If you can do this, I would highly recommend it. vector is much nicer and safer to deal with than an array you have to allocate yourself with new.

    Otherwise, try this:

    typedef int inner_array_t[3];
    inner_array_t *myArray = new inner_array_t[mySize];
    

    And since you don't want to use a typedef for some odd reason, you can unwrap it like so:

    int (*myArray)[3] = new int[mySize][3];