Search code examples
c++memory-managementdynamic-memory-allocationdynamic-arrays

C++ dynamically allocated array of statically dimensioned arrays


I need to create a structure that holds a variable number of 'char[2]'s, i.e. static arrays of 2 chars.

My question is, how do I allocate memory for x number of char[2].

I tried this (assuming int x is defined):

char** m = NULL;
m = new char[x][2];
...
delete [] m;

(it didn't work)

I realise I could use std::vector<char[2]> as a container, but I'm curious as to how it would be done with raw pointers.

I am very new to C++ and trying to learn.


Solution

  • In your code, the type of 'm' doesn't match your 'new' call. What you want is:

    char (*m)[2] = NULL;
    m = new char[x][2];
    ...
    delete [] m;
    

    m is a pointer to arrays of 2 chars, and you call new to get an array of x arrays of 2 chars and point m at the first one.