new/delete question

Started by
2 comments, last by SoGreen 23 years, 11 months ago
I''ll try to make this short and to the point If I have a declaration that looks like this: GameSquare BoardGrid[BOARD_WIDTH][BOARD_HEIGHT]; (GameSquare is a class which describes individual pieces on the GameBoard, obviuosly ) would I need to do this : for (int x=0; x < BOARD_WIDTH; x++) { for (int y=0; y < BOARD_HEIGHT; y++) { location.y = y; location.x = x; BoardGrid[x][y] = new GameSquare; } } or would it be fine with just the declaration It seems to me that new is just another way to declare a variable? p.s the code above came from here http://www.gamefoo.org/gp/gp_article1.html Thanks in advance
There's always something smaller and something bigger. Don't sweat the small stuff and don't piss off the big stuff :)
Advertisement
Your array objects are of the GameSquare class. No need to call ''new'' to allocate memory.

If your array were of pointers, like this:

GameSquare* BoardGrid[WIDTH][HEIGHT];


then you would need to use ''new''.

---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!
Another way to create it would be
GameSquare BoardGrid[][] = new GameSquare[BOARD_WIDTH][BOARD_HEIGHT];
if you wanted to do dynamic allocation.

new isn''t a way to declare a variable, it is a way to reserve memory for that variable.

when you do something like:
int i;
you declared(defined, actually reserved memory for it) the variable i;
int *pi;
you declared a variable whose type is a pointer to int;
however, is isn''t pointing to a valid int. You can then either make it point to an valid int like this:
pi = &i
or create a new int and make pi point to it, like this:
pi = new int;
anyway, allways remeber to use delete on any variable you allocated with new
delete pi;
(or delete [] parrayi; , if you allocated it like parrayi = new int[5]; )
When you declare a variable like
GameSquare BoardGrid[BOARD_WIDTH][BOARD_HEIGHT];
you are declaring a two imensional array of Board_width X board_height GameSquare''s;

When you declare a variable like
GameSquare *BoardGrid[BOARD_WIDTH][BOARD_HEIGHT];
then you are declaring a two imensional array of Board_width X board_height pointers to GameSquare, but not actually creating the GameSquare''s. Those pointers are just sitting there pointing somewere, but just follow them and you program is likely to end in a blue fireball (well more like a dialog box, actually).
so then, as (very well pointed by mossmoss) you have to create each of the gamesquare''s with new.

Sorry if this wasn''t to the point, or/and if you allready knew all this. Better safe that crashed
Thanks for the info guys your explanation was exatly what I needed. Think I got it now.

Damn MSDN is to wordy for the high school educated likes of me
There's always something smaller and something bigger. Don't sweat the small stuff and don't piss off the big stuff :)

This topic is closed to new replies.

Advertisement