Tyler Littlefield wrote:
> I still haven't figured out why people avoid type casts like the plague. 
> You'll survive through their usage. If you type cast things just to "make 
> them work," then it is bad practice, but for something like that it's 
> harmless. People suggested wrapping the array up in a struct/class, which 
> requires an object per-array that you want to pass around, (tacky?). People 
> have also suggested containers. As he hasn't gotten the hang of pointers 
> quite yet (or so it seems from post), I'd assume that he'd like to just stick 
> to a 2-d array, and not some "better method."
> 
> 
> Thanks,
> Tyler Littlefield
> http://tysdomain.com

Hey, I'm a typecasting guru.  But I don't like them - they make code 
look ugly.  And it does stop the compiler from reporting bugs in the 
code at _compile time_ vs. you having to find scour the code to find 
them later.  I say:  Let the compiler do the heavy-lifting of finding bugs.

There ARE cases where a typecast is necessary but I'm pretty sure we are 
wandering off-topic.  The guy just wants to get his program working at 
this point.

colour *col = new colour[100];

Does the same thing as the previously mentioned typecast approach 
without the typecast.


If you REALLY want a 2D array, then you'll need something fancier:

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.16

The fastest approach (in terms of performance) would be to do a single 
allocation and then hook up the necessary pointers BUT the C++ compiler 
will definitely balk at that.  I imagine you would be required to 
typecast away every message AND use "placement new", which has its own 
can of worms.  This approach is not mentioned in the above discussion 
(even though it is one of the most accurate C++ resources on the 
Internet).  Probably because it is an advanced C++ topic (i.e. very few 
people ever need to use it) and placement new is to be avoided at all 
costs unless you are really, truly, absolutely, 500% sure you know what 
you are doing and there is no other way to do it.  This is just for 
future reference purposes.  You're interested in code working now.

A two allocation approach is the second fastest method.  Allocate a big 
block of pointers and then allocate all the memory those pointers will 
point to at one time and then point the pointers at the right spots in 
memory.

The slowest method is the allocation-per-row approach, but is perhaps 
easier to understand than the other two.  You allocate enough space for 
a bunch of pointers that represent the rows and then, for each row, you 
allocate enough space for the columns for that row.

Of course, don't forget to 'delete' (delete []) what you 'new' (new []). 
  This is where templates/classes come in handy.  They can manage both 
aspects.

-- 
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197

*NEW* MyTaskFocus 1.1
Get on task.  Stay on task.

http://www.CubicleSoft.com/MyTaskFocus/

Reply via email to