|
-
November 20th, 2003, 03:15 AM
#1
Data structure prototype
Hello,
I got a third party prototypes declaration as follow:
Code:
typedef struct mydata{
DWORD Length; //length of data field in bytes
BYTE Data[1]; // the data itself, variable length
}MYDATA
My question is why the Data is an array of 1???, if it is supposed to be of variable length, of value Length., as stated in the comments??
-
November 20th, 2003, 05:58 AM
#2
Because 1 is the smallest dimension for the array that allocates space for it. The way these things work is that the struct is declared with an array of size 1 (as the last member). When the memory for the struct is allocated it can be bigger than the structs declared size allowing access to further array elements.
eg. MYDATA *p = malloc(sizeof(MYDATA) + 100;
now the array indexes could range from 0 to 100.
The Length field is used to convey the number of elements that are accesible in the array.
Dave Mclelland.
-
November 20th, 2003, 10:14 PM
#3
the following achieve the same purpose, why not use the following style instead?
Code:
typedef struct mydata{
DWORD Length; //length of data field in bytes
BYTE * Data; // pointer to data
}MYDATA
-
November 20th, 2003, 10:41 PM
#4
Search google for "struct hack". You will find many hits and lots of information on why this strange way of setting up a structure is done.
Regards,
Paul McKenzie
-
November 21st, 2003, 03:40 AM
#5
May be just because BYTE* pointer occupies sizeof(WORD) bytes but BYTE occupies only 1. Further, due to different word sizes, sizeof structure does not remain constant - for compatibility between platforms, this may be imposed.
-
November 21st, 2003, 04:45 AM
#6
Also changing the type from BYTE to BYTE* moves the actual data out of the struct.
Dave Mclelland.
-
November 21st, 2003, 07:17 AM
#7
Originally posted by Ajay Vijay
BYTE* pointer occupies sizeof(WORD) bytes
Code:
sizeof( WORD ) = 2 bytes
sizeof( BYTE* /* or any other pointer on Win32 */ ) = 4 bytes
sizeof( BYTE** /* or any other pointer on Win32 */ ) = 4 bytes
Thought for the day/week/month/year:
Windows System Error 4006:
Replication with a nonconfigured partner is not allowed.
-
November 23rd, 2003, 06:38 AM
#8
Sorry, but I meant with word size as per the platform and not the WORD datatype. In other words what 'int' occupies (Generally) on various OSs.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|