This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re[2]: How is a structure stored in memory?


Hi Dustin,

  Thanks for the answer.

  Very useful. I think I understand the offsetof macro... tricky,
  smart ;-)

     offset = (size_t) &((struct mystruct *)0)->B

  I will use it to continue understanding how structures are stored in
  memory.


Miguel Angel

     

Tuesday, April 6, 2004, 5:41:20 PM, you wrote:


DL> hi,

DL> maybe the "offsetof" macro will help you.

DL> it's sort of like "sizeof", except it tells you the offset of a variable
DL> within a structure.

DL> for example,

DL> struct mystruct {
DL>   unsigned int A;
DL>   char* B;
DL> };

DL> mystruct st;
DL> char* pB = (char*)&st + offsetof(struct mystruct, B);


DL> should set "pB" to be a pointer to member "B" within structure "st".

DL> you can find the definition of "offsetof" in "stddef.h" - you should be
DL> able to understand how it works.

DL> cheers,
DL> dstn.



>> Hello experts,
>>
>>   I have a problem ;-) I have a structure, its first field being a 8 bits
>>   type.
>>
>>     struct {
>>       U8  firstfield;
>>       .
>>       .
>>       .
>>     } st;
>>
>>     char* p = &st;
>>
>>   If I access the structure through a char pointer, am I accesing the
>>   first 8 bits field?? The first field will always be stored at the
>>   first byte (the one pointed by p)? This depends on the compiler?
>>
>>   The origin of the problem: I have a function with an only one
>>   argument, but I have to pass several kind of types through that
>>   argument. I first thougth the argument to be a union containing all
>>   the possible types. But it is really a lot of types.
>>
>>   I try the argument to be a char array. I will pass a first byte
>>   being a kind of index to identify the type. Following the first byte
>>   it is the type byte per byte. Inside the function I can examine the
>>   first byte and decide to do a cast, according to the correct type,
>>   to format the rest of bytes.
>>
>> Thanks a lot,
>> Miguel Angel
>>





Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]