Reputation: 3
I a problem on struct alignment. It seems no matter what I do the compiler inserts a byte between the two fields of the struct. This is a sample of the output
4 +j 4 +++ 40004 ......... 4
5 +j 5 +++ 50005 ......... 5
6 +j 6 +++ 60006 ......... 6
7 +j 7 +++ 70007 ......... 7
8 +j 8 +++ 80008 ......... 8
9 +j 9 +++ 90009 ......... 9
The byte 00 is inserted between the re and im fields of the H struct. How I can stop the compiler doing this to H so that so that the pointer pW can read both fields as 32 bit through the pointer pW?
Maybe I need to change the size of the 3d-array. If there is a way without changing the array size would be great.
#include <stdio.h>
#include <stdlib.h>
#define NA 4
#define NS 3
#define NF 5
typedef struct {
short re;
short im;
} cint16 ;
typedef struct
{
cint16 H[NRx][NSTS][NFFT];
} AAA;
AAA H;
AAA * pH = &H;
int main(void)
{
int i, j, k, n, m;
cint16 * pC;
int * pW;
n = 0;
for(i=0; i<NA; i++)
{
for(j=0; j<NS; j++)
{
for(k=0; k<NF; k++)
{
H.H[i][j][k].re = n ;
H.H[i][j][k].im = n;
n++;
}
}
}
pC = &H.H[0][0][0];
m = 0;
for(k=0; k<NA; k++)
{
for(i=0; i<NS; i++)
{
for(n=0; n<NF; n++)
{
printf("%02d ", pC[m].re );
printf("+j%02d,", pC[m].im );
printf(" ");
m++;
}
printf("\n");
}
}
printf("\n\n");
pW = (int *)&H.H[0][0][0];
pC = &H.H[0][0][0];
m = 0;
for(k=0; k<NA*NS*NF; k++)
{
printf("%2X ", pC[m].re );
printf("+j%2X", pC[m].im );
printf(" +++ ");
printf("%X ", pW[m] );
printf(" ......... %d \n", m);
m++;
}
exit (0);
}
Upvotes: 0
Views: 255
Reputation: 183968
You misinterpret the output.
printf("%X ", pW[m] );
prints the four bytes of the struct as an unsigned int
in hexadecimal representation
4|00|04
The first 4
is from the one non-zero byte of the struct member corresponding to the higher-order bytes of the unsigned int
(whether that's re
or im
depends on endianness), the next two bytes, 00
and 04
are from the two bytes of the other member.
There is no byte inserted between the members, there is one byte (and one nibble) not printed out due to the suppression of leading zeros.
Upvotes: 1
Reputation: 409356
It depends on what compiler you are using. On GCC there is __attribute__ ((__packed__))
, on VC++ there is #pragma pack
.
There are probably many duplicate questions here on SO that shows how to use those.
And a slight note of warning: Using a 32-bit integer to access two 16-bit values will depend much on the byte-ordering of the underlying platform. If you e.g. send this structure over the Internet or by file, you have to make sure you convert it properly.
Upvotes: 0