Re: [Hampshire] [Slightly OT] Arduino coding help - pointers…

Top Page

Reply to this message
Author: Chris Liddell
Date:  
To: hampshire
Subject: Re: [Hampshire] [Slightly OT] Arduino coding help - pointerstostructs
On 03/08/2010 14:30, Hugo Mills wrote:
> On Tue, Aug 03, 2010 at 02:19:32PM +0100, Chris Liddell wrote:
>> Declarations like your code don't declare variables comprising that
>> number of bits, they still are still the size of the base type (in this
>> case unsigned int). All the bit length option does (if supported by the
>> compiler) is restrict the maximum value of the field (and sometimes not
>> even that - many compilers ignore it completely).
>>
>> So your structure is not 16 bits long, it's 192 bits long.
>
>    Not true, at least with gcc 4.4.4:

>
> hrm@shades:~$ cat <<EOF >foo.c
>> #include <stdio.h>
>>
>> struct received_data {
>>     unsigned int start:1;
>>     unsigned int address:4;
>>     unsigned int command:5;
>>     unsigned int flags:4;
>>     unsigned int padding:1;
>>     unsigned int parity:1;
>> };

>>
>> int main(int argc, char* argv[])
>> {
>> printf("%d\n", sizeof(struct received_data));
>> return 0;
>> }
>> EOF
> hrm@shades:~$ gcc foo.c
> hrm@shades:~$ ./a.out
> 4


Ah, that's interesting. It *definitely* used to use the base type.

Mind you, four bytes is rather strange, since that doesn't seem to fit
with the structure element alignment - I'd have thought six bytes would
be the minimum size it could be. I *thought* gcc at least defaulted to
processor word alignment.

Chris