Multidimensional Dynamic Memory Arrays

Any way to make a multi dimensional dynamic array?

1
2
3
4
5
6
typedef unsigned char byte;
byte * BitmapArray;

void whatever() {
     BitmapArray = new byte[5][5];
}


???
you can use the new instruction only to allocate object of a class type,
you defined byte as a unsigned char, this is a primitive type, it's not a class so it doesn't work.

you may use the C calloc(...) function but it's not very simple at first sight

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream.h>

typedef unsigned char byte;

byte ** createByteMatrix(unsigned int rows, unsigned int cols) {
	byte ** matrix;
	matrix = (byte **) calloc(cols, sizeof(byte *));
	for(unsigned int i = 0; i < cols; i++)
		matrix[i] = (byte *) calloc(rows, sizeof(byte));
	return matrix;
}

void main() {
	byte ** BitmapArray;
	BitmapArray = createByteMatrix(5, 5);
	BitmapArray[0][0] = 0;
}


I think you may start with studying the malloc(), realloc(), calloc(), free() functions of the C language on this site.
You can find these functions in: Reference->C Library->cstdlib
in the paragraph "Dynamic memory management"

I just give you a simple example here:

1
2
3
4
5
6
void main() {
	byte * str;
	str = (byte *) calloc(100, sizeof(byte));	// this is specific for arrays
	// or: str = (byte *) malloc(100);		// this is only for byte arrays
	free(str);
}


I hope it can help you!
Good luck!
Thanks!
Mayflower i think you needed this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream.h>

void main() {
	const int rows = 4;
	const int cols = 4;

	// declaration
	int ** a;

	// allocation
	a = new int*[rows];
	for(int i = 0; i < rows; i++)
		a[i] = new int[cols];

	// initialization
	for(int j = 0; j < rows; j++)
		for(int i = 0; i < rows; i++)
			a[i][j] = 0;
}


I'm very sorry but i discovered it just now.
I hope this helps you.
Last edited on
Exactly, that's the proper way.
And remember, that you can't just delete[] a multidimensional array - you need to delete it row by row, just as you create it.
Have fun.
M
Topic archived. No new replies allowed.