Re: struct padding ???
- From: jt@xxxxxxxxxxx (Jens Thoms Toerring)
- Date: 31 May 2008 16:12:29 GMT
vikas talwar <vikas.talwar@xxxxxxxxx> wrote:
Can you please explain me how the 'C' compiler allocate memory to
'struct'.
Please go thu the example below and pls suggest me the solution for my
problem.
Here is my structure definition
struct my_dev {
char abc;
} ;
and now when I do
printf("size=%d\n", sizeof(struct my_dev));
output is: 4
But I expect the size of struct = '1'.
Is there any trick to get the struct to occupy memory with pad of 1
byte and not 4 bytes..
The compiler is obviously putting in 3 padding bytes after the
'abc' element of the structure. It does that to make sure when
you create an array of such structures all the structures of
the array end up on correctly aligned memory positions. If
it wouldn't do that something simple as
my_dev xxx[ 2 ];
xxx.abc = 'c';
could lead to a crash of the program, at least on your machine
(on mine the sizeof for the structure is repoted as 1, so on
my machine it doesn't seem necessary to insert padding bytes).
For the same reason also padding bytes can appear between the
elements of a structure.
There is no C standard compliant way to elimintae padding bytes.
Some compilers have some extra options to avoid the addition of
padding bytes, for e.g. gcc you would have to add
__attribute__((packed))
directly after the structure declaration) but, unless you know
exactky what you're doing and the trouble you can get into with
that I can only recommend not to use it. Perhaps you should
tell what exactly you want to achieve that would require the
elimination of padding bytes and perhaps there's a better way
to do it.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.
- Follow-Ups:
- Re: struct padding ???
- From: Jens Thoms Toerring
- Re: struct padding ???
- References:
- struct padding ???
- From: vikas talwar
- struct padding ???
- Prev by Date: Re: strtok question
- Next by Date: Re: function
- Previous by thread: struct padding ???
- Next by thread: Re: struct padding ???
- Index(es):
Relevant Pages
|