On Sat, 18 Feb 2012 09:35:04 -0800 (PST), aleksa <
alek...@gmail.com>
wrote:
>typedef struct { // 16 bits, one WORD
> unsigned short B4:4; // (using GCC)
> unsigned short B9:9;
> unsigned short B1:1;
> unsigned short B2:2;
>} S1;
>
>typedef struct {
> S1 q1, q2;
>} S2;
>
>static S2 table[2]= {
> {{1,1,1,1}, {1,1,1,1}}, // just test values
> {{1,1,1,1}, {1,1,1,1}}
>};
>
>unsigned short getq1 (int i)
>{
> unsigned short bit16;
>
> // ERROR HERE
> // aggregate value used where an integer was expected
> bit16 = (unsigned short) table[i].q1;
table is an array of S2.
table[i] is a particular S2 in that array.
table[i].q1 is the first S1 in that S2.
S1 is a struct. Structures and arrays are aggregates by definition.
You need table[i].q1.B4 or whichever B? you are interested in.
The cast should be unnecessary since all the scalar objects have the
same type.
>
> return bit16;
>}
>
>
>Someone has already suggested using unions,
>
> typedef struct {
> unsigned short B4:4;
> unsigned short B9:9;
> unsigned short B1:1;
> unsigned short B2:2;
> } BitField;
>
> typedef union {
> BitField bits;
> unsigned short all;
> } S1;
From this I gather you don't care about the individual bit fields but
really want the 16 bit composite value.
>
> typedef struct {
> S1 q1, q2;
> } S2;
>
>but I don't know how to initialize the table:
>
> static S2 table[2]= {
> {{1,1,1,1}, {1,1,1,1}}, // just test values
> {{1,1,1,1}, {1,1,1,1}}
> };
>
>That doesn't work anymore, i get
>"missing braces around initializer"
My compiler doesn't produce this error and accepts the definition
int i = table[0].q1.all;
in main(). However -
The outer pair of braces (lines 1 and 4) simply bound the
initialization text.
The beginning and ending braces on line 2 specify that the data
applies to table[0]. The ones on line 3 specify table[1].
table[0] consists of 2 objects, each an S1.
The first pair of inner braces on line 2 bound the initialization for
table[0].q1. q is a union so you are attempting to initialize the
first member. That member is an aggregate of type BitField. To
initialize this aggregate, you need another pair of braces. Try
static S2 table[2]= {
{{{1,1,1,1}}, {{1,1,1,1}}}, // just test values
{{{1,1,1,1}}, {{1,1,1,1}}}
};
which my system also accepts. Both version print 24593 (0x6011) for i
which does not match my expectations, even for a little endian system.
--
Remove del for email