http://GameProgrammer.Com

Programming

GP Mailing List
     Thread Index
     Date Index

ATXGPSIG List
     Thread Index
     Date Index

Google
>

Home

Wise2Food



[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: C++ help



--- Sponsor's Message --------------------------------------
Who Are the Top Dogs?
Find out about the best newsletters and discussions!
http://click.topica.com/aaaa4qbUrGczbU68iFb/TopDogs
------------------------------------------------------------
In a message dated 3/14/01 3:42:47 PM Central Standard Time,
tomdelduca@cs.com writes:


dynamic_map = new char[ms_x] [ms_y];  (ms_x and ms_y passed into function)

but this gives me a 'constant expression required' error.
any help would be appreciated.


Ah, if only "new" was a bit more dynamic. Well, sorry to tell you this, but
you must give a constant expression for "ms_x." In other words, you can't
just say something like...

char *Buffer=new char[a][b][c];

...if a and b are variables. You HAVE to say something like this:

char *Buffer=new char[5][9][c];

Therefore, the rule about new is that only the last dimension (the "[c]") can
be a variable. All preceding dimensions must be constants. There are a few
ways around this. You could say:
#define a      5
#define b      9
...and then the first expression (char *Buffer=new char[a][b][c]) would be
valid. This would also work:
const a=5, b=9;
These work because the compiler treats a and b as constants - not variables
that can change during runtime. However, I bet you would prefer to
dynamically (use variables) allocate memory for that array of yours. No
problem. Here's how:
char *Buffer=new char[a*b*c];
OK, so you're not REALLY defining a three-dimensional array, but rather you
are defining a one-dimensional array that can hold all the information the 3D
array would hold. Just one thing to keep in mind. Say you wanted to access
Buffer[x][y][z]. You can't just type that in because you do NOT have a 3D
array. Instead, access this memory location:
Buffer[x*b*c+y*c+c];
TADA! The above command is just like accessing Buffer[x][y][z]. So, if you
allocated your array like this:
dynamic_map = new char[ms_x*ms_y];
This would be perfectly legal. And, if you wanted to access
dynamic_map[c][d], you would instead access dynamic_map[c*ms_y+d].

So, in practice, it is usually beneficial NOT to rely on multi-dimensional
arrays. Instead, define it as a big one-dimensional array that can store all
those values, and develop a way of organizing that data. The above method
works well.

Hope this helps,
-Ender Wiggin
------------------------------------------------------------
$$   Earn Extra Income As A Mystery Shopper!   $$
   http://www.topica.com/lists/Mysteryshopper/
$$ 100's Of National Assignments Posted Daily! $$
____________________________________________________________
T O P I C A  -- Learn More. Surf Less. 
Newsletters, Tips and Discussions on Topics You Choose.
http://www.topica.com/partner/tag01