Archived

This topic is now archived and is closed to further replies.

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

This topic is 5094 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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);

Share this post


Link to post
Share on other sites
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];

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites