MD arrays as class members

how do i declare a multi-dimensional array as a member object of a class when i don't know the size ahead of time?

for example:
1
2
3
4
5
6
7
8
class example{
	int array[height][width];

	example(int height, int width){
		int array[height][width];
	}
	~example()
}


i know the above code is wrong, putting the height and width variables before the constructor, but i just wanted to try to be clear with what i'm attempting to do.

i can't find information on this anywhere and it's beginning to bother me.
Last edited on
are you suggesting i not use stock MD's, or are you trying to get me to read something specifically within that link?
There are several ways shown to write a dynamic 2d array. Choose whichever seems best to you.
none of the examples in the referenced link (which i've already read) address the issue. convincing me to not use stock MD arrays because of the "evils" of them does nothing to help me understand WHY it isn't working right or HOW to employ it correctly.

if there is no straight-forward way to do it, you can just say that, or give me a useful work-around... OR, at the very least tell me what you want me to look at with the page that you've pointed me to.

otherwise, i don't see how arbitrarily pasting a link will help anyone. if you don't feel like you can put forth the effort to answer the question, you could've just not contributed.
maybe i just don't understand how to properly use classes.
int array[height][width]; is a static array.
It doesn't matter how many dimensions it has, array declared as Type Name[size1][size2][size3]...etc.; is static, meaning that the size of each dimension has to be known at compile time.
A dynamic 1D array is either int* array = new int[size]; or std::vector<int> array;. A dynamic MD array is a combination of those, as the article shows.
There are several ways shown to write a dynamic 2d array. Choose whichever seems best to you.
Last edited on
to be clear,
1
2
3
int height = 3;
int width = 4;
char array[height][width];


that is a static array?

and if so, are you saying there is no way to use a class to declare "static" MD arrays similar to my original example?
no, that is no valid as height and width are not constants. If they were declared as const int, it would work though.
and I'm not saying you can't have a static array in a class. The problem is tat a static array must have a constant size and only a dynamic array can have variable size.
as an example you could have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class example
{
	example(int height, int width)
		: m_height(height), m_width(width)
	{
               m_array = new int*[height];
		for (int i = 0; i < height; i++)
		{
			m_array[i] = new int[width];
		}
	}
	~example();

	int** m_array;
	unsigned int m_height;
	unsigned int m_width;
};


then use m_height and m_width to keep track of how long the array is.
Last edited on
Topic archived. No new replies allowed.