简体   繁体   中英

byte array to struct - how to access struct members

I have the following byte array that I am casting to the struct below: ** I know it's not in the proper format here "0x80", etc, but in my code it is.

unsigned char ReadBuffer[512] = { 80 00 00 00 50 00 00 00 01 00 40 00 00 00 01 00 00 00 00 00 00 00 00 00 FF F2 00 00 00 00 00 00 40 00 00 00 00 00 00 00 00 00 30 0F 00 00 00 00 00 00 30 0F 00 00 00 00 00 00 30 0F 00 00 00 00 33 20 C8 00 00 00 0C 42 E0 2A 0F 9F B9 00 00 FF}

typedef struct MFT_ATTRIBUTE {
    DWORD dwType;
    DWORD dwFullLength;
    BYTE uchNonResFlag;
    BYTE uchNameLength;
    WORD wNameOffset;
    WORD wFlags;
    WORD wID;
    LONG n64StartVCN;
    LONG n64EndVCN;
    WORD wDatarunOffset;
    WORD wCompressionSize;
    BYTE uchPadding[4];
    LONGLONG n64AllocSize;
    LONGLONG n64RealSize;
    LONGLONG n64StreamSize;
} MFT_ATTRIBUTE, *P_MFT_ATTRIBUTE;

MFT_ATTRIBUTE* mft_attribute = (MFT_ATTRIBUTE*)ReadBuffer[0];

When I try to print the members, for some reason I get the some kind of incremental values:

printf("%x ",&mft_attribute->dwType);
printf("%x ",&mft_attribute->dwFullLength);
printf("%x ",&mft_attribute->uchNonResFlag);
printf("%x ",&mft_attribute->uchNameLength);

Output:
0x80 0x84 0x88 0x89

Can someone help me clarify this?

You are printing addresses, not values. That's why the output is increasing this way:

  • 0x80 - base address, same as the first member dwType
  • 0x84 - second member, dwFullLength, sizeof (dwType) apart from start
  • 0x88 - third member, uchNonResFlag, again an offset of 4, sizeof(dwFullLength)
  • 0x89 - 4th member, the offset is 1, which is sizeof (uchNonResFlag)

Remove the & before mft_attribute in your output code:

printf("%x ", mft_attribute->dwType);
printf("%x ", mft_attribute->dwFullLength);
printf("%x ", mft_attribute->uchNonResFlag);
printf("%x ", mft_attribute->uchNameLength);

You are casting the first element of the array to a pointer to your struct.

MFT_ATTRIBUTE* mft_attribute = (MFT_ATTRIBUTE*)ReadBuffer[0];

You want to cast a pointer to the first element :

MFT_ATTRIBUTE* mft_attribute = (MFT_ATTRIBUTE*) (ReadBuffer + 0);

Also as @Wolf pointed out this prints pointers not values pointed to:

printf("%x ",&mft_attribute->dwType);

You need instead

printf("%x ", mft_attribute->dwType);

Change your cast to the following:

MFT_ATTRIBUTE* mft_attribute = (MFT_ATTRIBUTE*)&ReadBuffer[0];

or to

MFT_ATTRIBUTE* mft_attribute = (MFT_ATTRIBUTE*)ReadBuffer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM