Re: querry related to structure padding
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sun, 19 Mar 2006 20:39:50 GMT
Simon Biber <news@xxxxxxxxx> writes:
Lalatendu Das wrote:[...]
hi let's say i have a structure
struct test {
int A;
char B[5];
int C;
};
this above structure defination always going to take 16 byte in
memeory in whatever manner we align the member variables while
declaring a variable to it .
because variable 'A' going to take 4 byte then four charachter of
array gonna take another 4 bytes but the remaining will take also 4
bytes due to four byte alignment nature of compiler .
and last four byte by integer C .
what i want is there any way i can start storing integer C just after
the storing completion of array B's last element i.e. B[4] , so that i
can suppress padding . Any program which make memory manager store in
the above manner is most welcome.
Ok, declare your struct like this:
struct test {
int A;
char B[5];
unsigned char C[sizeof (int)];
};
The compiler is still free to insert padding between B and C, or after
C, either because it can make the code potentially more efficient (for
example, memcpy() might be faster for aligned character arrays) or
because the compiler writer was in a funny mood that day.
If you want to fully control the layout of a structure, declare the
whole thing as an array of unsigned char, define the offsets and sizes
yourself, and write your own code to extract whatever data you need.
That's the only truly portable way to match an externally defined data
layout (assuming consistent byte sizes, and assuming you're dealing
correctly with byte ordering).
Or you can use some compiler-specific tricks to control the layout
(which will almost certainly result in slower code).
But the real question (to which I don't recall seeing an answer) is
*why* the OP wants to eliminate padding between the structure members.
The compiler inserts that padding for very good reasons; are you sure
that you know better than the compiler does how the structure should
be laid out? Quite possibly you do, in which case you'll need to do
something non-portable and/or ugly -- but if you just have a general
idea that you want to save space, consider letting the compiler do its
job.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- querry related to structure padding
- From: Lalatendu Das
- Re: querry related to structure padding
- From: Simon Biber
- querry related to structure padding
- Prev by Date: Re: how to count rows and columns of integers/doubles in a file?
- Next by Date: Re: how to count rows and columns of integers/doubles in a file?
- Previous by thread: Re: querry related to structure padding
- Next by thread: Re: querry related to structure padding
- Index(es):
Relevant Pages
|