Multidimensional arrays with new...

Alright, I am working on a new class that will need an array of unsigned char's that will be 6 characters in length each. Is it possible to do something like the following?
1
2
3
unsigned char *pArray[6];

pArray = new unsigned char[100];

The array will always be "[some number][6]" and I want to avoid doing it the following way.
1
2
3
4
5
unsigned char **pArray;

pArray = new unsigned char*[100];
pArray[0] = new unsigned char[6];
pArray[1] = new unsigned char[6];

I can loop through to allocate each pointer to 6 characters, but that's a lot of code and cleanup. Isn't there a better way to do this?
If the array will always be of the same size, why are you using dynamic allocation? Why not just do unsigned char pArray[100][6];? Unless, of course, you want to return the array, in which case, dynamic allocation is the way to go.

Isn't there a better way to do this?
Ehh... Sort of. It requires even more code, though, and it's not too pretty.
The easiest way is a simple for:
1
2
for (int a=0;a<100;a++)
    pArray[a]=new unsigned char[6];


You might want to typedef unsigned char uchar;, by the way.
Last edited on
well Sephiroth, with power comes responsibility... so... if your program needs to play with memory, in a free fashion... allocation and clean up code will be always there...
you can create a one-dimensional array char[100*6] but then you need to write your own functions to properly adress individual entries, or use slices. Another option is to use the multidmensional array libraries where all that is done for you, like blitz for example.
You could do something like this:

1
2
3
4
5
6
int** pArray = new int*[100];

for(int i = 0; i < 100; i++)
{
    pArray[i] = new int[6];
}


Make sure you free your memory properly as well.
It won't always be 100 of those arrays. Each entry will always be 6 characters long, but the data in the file I am reading contains between 0 and 555 entries in each object. One object may be char[4][6] and the next would be char[128][6]. That was my issue. I currently do the "char **pArray" method, but I was hoping I could do something quicker, like "char *pArray[6]" or something.
yay for typedef:

1
2
3
4
5
6
7
8
typedef char char6[6]; // come up with a better name than 'char6' if you like

//--------------------
char6* myarray = new char6[100];

myarray[88][5] = '!';

delete[] myarray;


EDIT: at least... I *think* this works. I didn't actually test it. XD
Last edited on
That works fine, and I may use it. I am probably just going to make a single pointer and allocate 6 * number of records, then locate my record using id * 6. The only thing I have to figure out then is how to read from that spot and only read six characters. Shouldn't be too hard though.
Topic archived. No new replies allowed.