Packed C-structures in Interactive UNIX

Jens Groth Andreasen jga at jt.dk
Mon Dec 10 22:59:09 AEST 1990


I'm developing an application for a PC running INTERACTIVE UNIX System V/386 
Release 3.2 using the standard C compiler ('cc').
For reasons beyond my control, some of the structures I use must be 
byte aligned (i.e. no padding with unused bytes). I was hoping that
'#pragma pack(1)' could do the job for me, but as the following example show
the directive doesn't work 100% correctly.

/* EXAMPLE BEGINS HERE */
#include<stdio.h>
#pragma pack(1)

typedef struct {
     char e1;
     int e2;
} S1;

typedef struct {
     char e1;
     int e2;
     char e3;
} S2;

typedef struct {
     S1 s1;
     S2 s2;
} S3;

static S3 s3 = {
	'c', 4711,
	'q', 117, 'w'
};

main()
{
printf("%c %i\n%c %i %c\n", s3.s1.e1, s3.s1.e2,
			    s3.s2.e1, s3.s2.e2, s3.s2.e3 );
}
/* END OF EXAMPLE */

When I compile this with 'cc example.c', the output of the program will be: 
g 1962934290
 1902313472 w
/* END OF OUTPUT */

If I remove the #pragma pack(1), the output will be the expected, but if I
now compile the (modified) program with 'cc example.c -Zp1' ( the -Zp[1|2|4]
option will byte-, two-byte- or word-align members of structures resp.) I get 
the strange output from before.

Can anyone running on a similar system recreate this?
Can anyone explain this?

If I initialize the structure by assignments (like 's3.s1.e2 = 4711') I get
the right output (with or without the #pragma pack(1)).

Please mail me even if you respond by posting, I'll post a summary of the 
responds.

Regards, Jens.

----------------------------------------------------------------------
email: jga at jt.dk
       jgroth at daimi.aau.dk  (this address is the most reliable one)

FAX: +45 86 29 39 77
Phone: +45 86 29 33 66 ext. 6925  (open 7.15 - 15.15 GMT)

Letter post: Jens Groth Andreasen
	     Jutland Telephone
	     Sletvej 30
	     DK-8310 Tranbjerg J.
	     Denmark (Europe)
----------------------------------------------------------------------



More information about the Comp.lang.c mailing list