Array vs Structure
10 messages in this thread
I am storing information for a game map with things like Terrain…
Is there any advantage to an array over a structure as far as size or
accessing. I am a novice C user and the information on each of these
ways to store data is small, from what I can find. Since storing and
retreiving information is the largest part of my programI don't want
to screw it up.
The answer is: it depends. 🙂 If you're storing a number of different items
at each cell location, then you might want a matrix of structures. Or, you
could have several matrices configured in the same dimensions, each holding one
type of item.
You also need to consider whether your matrix is fixed or variable in
dimensions. If you're worried about speed then other questions come into play,
such as the ways you most often access the matrix. There are different
optimizations depending on whether you access the matrix randomly,
sequentially, by row or by column.
If you're new to all this, I'd stick with coding a fixed-dimension
doubly-dimensioned array of structures:
typedef struct {
int color;
int contents;
int who;
} cell;
cell Map[64][64];
My matrix is going to be defined one time and then accessed radomly. I am more
familiar with arrays, but the struct format seems like it has some neat
features. I guess I just need to decide if I really need to use it or not. :
)|(
Thanks for the info and I will ponder this some more.
Trust me, you want to learn how to use structures. For example, you can say
'person = Map[3][15].who;'. I also slipped in an example of 'typedef' that
should make your life easier.
I think what you're asking is:
Is it better to do this:
int larry[??];
float curly[??];
char mo[??];
or this:
typedef struct stooges {
int larry;
float curly;
char mo;
};
stooges abunchofthem[????];
In general, the answer is the latter. If that is not your questions then
hopefully somebody else will address it, or by all means please reask it.
That was my question. Is there any good books for info on using differernt data
structures?
I have a couple on using C, one is for Unix, but doesn't give any real examples
of how to use structures or arrays. The other book is C on the Amiga. It
mentions C data structures briefly.
Jim,
one that I find myself referring to is "Algorithms in C" by Robert
Sedgewick (Addison-Wesley ISBN 0-201-51425-7). Not only does it have all
the algorithms one might need for writing many programs, but it has some
excellent sections on the various data structures, their strengths and
weaknesses, and how to code them. Finally, it has tons of illustrations
showing how all this works. Very nice!
Brian
>Is there any good books for info on using differernt data structures?
Yes, but I'm not sure of which perspective you are coming from.
There are language neutral books which explain algorithms and data
structures in general. And of course there are more specific things
(including philosophically) relating to C.