You are not logged in.

1

Friday, June 25th 2004, 2:37am

Why occur this problem??

Sorry. I poor english.

I defined follow and some struct created.
My problem is size.
Indivisual size(BYTE, WORD, DWORD) is correct (1 ,2 ,4);
But struct size is incorrect.

//=================================================
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;

typedef _date {
WORD y; /* year */
BYTE m; /* month */
BYTE d; /* day */
BYTE w; /* week */
}Date;

qWarning("BYTE %d WORD %d DWORD%d\n"
,sizeof(BYTE),sizeof(WORD),sizeof(DWORD));

qWarning("Date size is %ld \n", sizeof(Date));
//===================================================

Result is
"BYTE 1 WORD 2 DWORD 4
Date size is 6 "

Why this problem occurs?
Correct result "Date size is 5", is right???

My works network protocol create and send and rceived.
So I create some date and rearrange.
So data size is important.
I'm using Qt 3.3.2 and running Gentoo Linux.

Posts: 2,162

Location: Graz, Austria

Occupation: Student

  • Send private message

2

Friday, June 25th 2004, 3:39am

This depends on a lot of things, for example compiler and optimization settings.

Simply put you cannot rely on memory layouts of structs.

Better read the 5 bytes and copy them into the fields of the struct, respectively write them one by one.

Btw, char is not guaranteed to be 1 byte, better use types like Q_UINT8

Cheers,
_
Qt/KDE Developer
Debian User

3

Monday, June 28th 2004, 2:27am

Thanks.

Thanks your reply...
So, How can I solve this problem?
Please your answer...
Thanks in advance.

  • "wysota" is male

Posts: 4,276

Location: Warsaw, POLAND

  • Send private message

4

Monday, June 28th 2004, 9:01am

RE: Thanks.

Either force BYTE to be really one byte or read the data from the stream byte by byte (instead of the whole struct at once) and then put the bytes into the struct as anda_skoa suggested. Also remember, that the network order of the bytes may be different than the order at the hosts machines (and both hosts may have different orders too), so reading/writing a whole struct is not a very wise choice because it can happen, that you read not the same data that you have written on the other end of the stream.

Guest

Unregistered

5

Monday, June 28th 2004, 11:05am

Use pragma pack(n).....

This is good solution.