This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: How is a structure stored in memory?
- From: Dustin Lang <dalang at cs dot ubc dot ca>
- To: Miguel Angel <miguel dot nunez at terra dot es>
- Cc: gcc-help <gcc-help at gcc dot gnu dot org>, ernenedelatribu at ya dot com
- Date: Tue, 6 Apr 2004 08:41:20 -0700 (PDT)
- Subject: Re: How is a structure stored in memory?
- References: <129127141437.20040406104924@terra.es>
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
>