A Simple Newbie C Question that I should know...

Started by
2 comments, last by Radagar 20 years, 2 months ago
Grr, this always annoys me. Why can''t I do this, and what''s the best way to get around it?

int xsize = 5;
int ysize = 5;

MapTile Map[xsize][ysize];
Of course this complains about needing const values when declaring an array. well, I''m reading in the X and Y values from my user, and I want to create an array of the entered size. I guess this is going to require pointers, I just want to know the easist way to do what I did above, only correctly =) Thanks.
WyrmSlayer RPG - In Early Development
Advertisement
MapTile* Map = (MapTile*) malloc(xsize*ysize*sizeof(MapTile));

Map[x][y] becomes Map[x*ysize+y]

When you''re done with the map, do not forget to do free(Map);
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thanks Fruny.

I know I said C, but I''m actually writing this in C++.

How would I format that using new and delete?

I did it like this, just want to make sure that''s correct.

CMapTile* Map = new CMapTile[xsize*ysize];
WyrmSlayer RPG - In Early Development
Yes that''s correct. Remember to use delete[] instead of delete to deallocate the arrays memory.

If you''re wondering why your original way didn''t work it''s because you try to create an array using variables to give the size. These variables can change at run time and when you do something like MapTile Map[2][2] in C++ it is allocated statically. That is the size of the array is hardcoded into the program and cannot be altered hence the values you give as the array sizes have to be constant(the way the memory is allocated to dynamic allocation will also differ, but I won''t get into that). If you put const in front of your two variable definitions, it should work. Though I believe you are trying to acomplish dynamic allocation (i.e. you can have different sizes depending on the size of the map) so Fruny''s way will work fine.

This topic is closed to new replies.

Advertisement