Advertisement

Trying to declare an array in a class constructor

Started by August 28, 2001 01:34 AM
14 comments, last by Gwargh 23 years, 5 months ago
I sort of need it in two dimensions, because I'm constructing tetraminos, so I have to know when to go to the next row... but I guess I could figure something out with just one dimension.

EDIT: Just thought of something... I can do what I want in one dimension more efficiently than I could with two if I make it an array of USHORTs. Okay, thanks everyone.

Edited by - Gwargh on August 28, 2001 5:45:40 PM
"These books suck."-- Zidane
So write an accessor function: something like

bool& Block::operator()(int x, int y) { return grid[(y * width) + x]; }

So then you could write
Block(10, 14) = true;
Or whatever.
Advertisement
Just to go a touch off topic, Gwargh, the errors in your anonymous post are because you put semicolons at the end of your #define statements.

#define is a instruction that defines substitutions in your code. So, you had something like:

#define WIDTH getwidth;

x = new something[WIDTH];

When the defined variable was substituted, you got:

x = new something[getwidth;];

So, apart from the problems that everyone else pointed out, you should take note of how #define works. Usually it is used to define constants in your code (although you should use the const keyword). For example,

#define PI 3.14

area=PI*r*r;

becomes...

area=3.14*r*r;

if you had done,

#define PI 3.14;

you would have got

area=3.14;*r*r;

which is a syntax error.

/my 2p
Regards,
Devore
Good catch, Devore. I missed that completely.
olp-fan mentioned this, but I don't think anyone elaborated: a multidimensional array is an array of arrays. So it works like this:

    bool ** array2d = new bool[width];for(unsigned int i = 0; i < width; i++){    array2d[i] = new bool[height];}    


Then you can access array2d normally, like array2d[x][y].

But be sure to delete it in your destructor:


    for(unsigned int i = 0; i < width; i++){    delete [] array2d[i];}delete [] array2d;    


Edited by - TerranFury on August 29, 2001 9:31:39 PM
I think you are able to declare an static array with variable subscript with C99 compilant compiler.

This topic is closed to new replies.

Advertisement