Re: How is a structure stored in memory?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



hi,

maybe the "offsetof" macro will help you.

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

for example,

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

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


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

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

cheers,
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 of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux