Mixing types in arrays
Steve Watt
steve at wattres.uucp
Fri Feb 15 16:32:23 AEST 1991
In article <22040 at hydra.gatech.EDU> cc100aa at prism.gatech.EDU (Ray Spalding) writes:
>I keep finding myself wanting to store shorts and longs (as well as
>chars) in arrays of char, such as in the following simple example.
[ stuff deleted ]
>But, are there other pitfalls? Systems on which this won't work? A
>better way?
One system that this won't work on is the IBM RT (at least under AIX), because
a non-aligned integer (read 32 bit) access will get *garbage* in various places.
It will produce 'fixed up unaligned access at xxxxxxxxx for pid xxxx' on the
DECStation, unless the message is turned off, and will probably blow in strange
and subtle ways on other RISC systems.
A better way? Use a struct? Probably not as compact, but *much* more obvious.
For example, the code (left to the reader) for the following definitions could
do (mostly) the same thing, but the search (even linear!) is quite a bit
quicker, since it isn't calling strlen all the time.
typedef struct {
long value;
char key[1];
} item;
item *data[1000];
Yes, you have to malloc a copy every time, but that's not so bad. But you
can easily play all of the various data structure optimization games from
here (binary searches with ordered list, etc...)
Have fun!
--
Steve Watt
...!claris!wattres!steve wattres!steve at claris.com also works
Never trust a computer bigger than you can lift.
More information about the Comp.lang.c
mailing list