At 9:48 AM +0100 2000/02/17, Aaron Ardiri wrote:
> > #define OffsetOf(type, member) ((UInt32) &(((type *) 0)->member))
> >
> > So in your example above, you would use OffsetOf(MyStruct, finalField) in
> > place of sizeof(MyStruct) throughout your code for accurate, predictable
> > results. "It's A Good Thing." -- Martha Stewart
>
> this will tell you how large the structure definition you have declared
> is, however if you want to know how much data is being stored in that
> array, you may wish to check how much memory is being occupied by the
> pointer reference "finalField".
>
> the true size (including the array) would be:
>
> OffsetOf(MyStruct,finalField) + // the stuff before the "array"
> MemPtrSize(struct.finalField); // the array that size is unknown
That can't work because struct.finalField is not a Memory Manager pointer; it's a
member field of a structure.
The true size of the record is simply MemPtrSize(theDatabaseRecordPointer) but this is
a chicken-and-egg problem if you're trying to allocate for the database record in the
first place. In that case you want OffsetOf(MyStruct,finalField) + (sizeof(SomeType) *
numberOfInstancesYouWant) which may or may not account for alignment padding depending
on your compiler options. (Did I say this was fun? Hmmm...)
> but then again, it all depends on how well the MemPtrSize() function
> works in this case.. if this does not work (i would not be surprised)
> then you can always have an extra field in the structure saying how
> large the array is?
Yes, that's the only way to know for certain how many MyStruct elements are actually
in the array, unless you're extremely careful to define SomeType such that its sizeof
allows consecutive instances to fall on the natural boundary of its first element
(assuming SomeType is a structure, not a simple data type). Unfortunately, that
behavior can't be enforced in C syntax.
I generally recommend adding both Count and Physical-size fields prior to any variable
length array of structures. This allows you to know 1.) the number of instances, and
2.) the beginning of each instance independent of alignment issues (most useful when
the last field of the instance is, for example, a single byte). This approach is a
reasonable compromise between the ability to cast a pointer to the instance as a
structure for run-time efficiency (speed), and the storage efficiency (space) used in
each record, especially if the structure is to be manipulated on a non-native
platform, or more generally by some other application.
Regards,
Jim Schram
3Com/Palm Computing
Partner Engineering
--
For information on using the Palm Developer Forums, or to unsubscribe, please see
http://www.palm.com/devzone/mailinglists.html