Re: struct with variable length member
From: Frank Hickman (fhickman_nosp_at_m_noblesoft.com)
Date: 03/20/04
- Next message: Carl Daniel [VC++ MVP]: "Re: Call ActiveX *.exe From VC++"
- Previous message: CheckAbdoul: "Re: struct with variable length member"
- In reply to: lavut: "struct with variable length member"
- Messages sorted by: [ date ] [ thread ]
Date: Fri, 19 Mar 2004 22:31:55 -0500
I think you want a union, not a struct, maybe...it depends on what it is
your trying to do?
typedef union
{
struct
{
WORD a1;
WORD a2;
};
DWORD a3;
}AAA;
typedef union
{
WORD b1;
AAA b2[1];
}BBB;
BYTE buffer[]= {
0x11, 0x22, 0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd
};
BBB* bbb= (BBB*)buffer; //cast to a union
int main( int argc, char* argv[] )
{
printf( "bbb->b1 = %x bbb->b2[0].a1 = %x bbb->b2[0].a2 = %x\n",
bbb->b1, bbb->b2[0].a1, bbb->b2[0].a2 );
printf( "bbb->b2[0].a3 = %x\n", bbb->b2[0].a3 );
if ( !getch() )
{
getch();
}
return 0;
}
produces...
bbb->b1 = 2211 bbb->b2[0].a1 = 2211 bbb->b2[0].a2 = 4433
bbb->b2[0].a3 = 44332211
HTH
--
============
Frank Hickman
NobleSoft, Inc.
============
Replace the _nosp@m_ with @ to reply.
"lavut" <anonymous@discussions.microsoft.com> wrote in message
news:28DE3E3A-D30C-4798-973D-CBAF5E76AEC6@microsoft.com...
> Consider this piece of code.
> Can somebody tell me why the output below gives the wrong result when I
defined
> struct AAA with a3 as a DWORD?
>
> #include <windows.h>
> #include <stdio.h>
>
> BYTE buffer[]={0x11, 0x22,
0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd};
> typedef struct {
> WORD a1;
> WORD a2;
> DWORD a3; //as a WORD output below ok, as a DWORD 4433 is not read
>
> }AAA;
>
> typedef struct {
> WORD b1;
> AAA b2[1];
> } BBB;
> BBB*bbb = (BBB*)buffer; //cast to a struct
>
> void main() {
> //with a3 as a WORD : 2211 4433 6655
> //with a3 as a DWORD: 2211 6655 8877 <----this is wrong, why?
> printf("%x %x %x", bbb->b1, bbb->b2[0].a1, bbb->b2[0].a2);
>
> }
>
- Next message: Carl Daniel [VC++ MVP]: "Re: Call ActiveX *.exe From VC++"
- Previous message: CheckAbdoul: "Re: struct with variable length member"
- In reply to: lavut: "struct with variable length member"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|