hi ,
I am having bit field packed in union of struct..
but not able to retrieve values correctly
/..........
Printable View
hi ,
I am having bit field packed in union of struct..
but not able to retrieve values correctly
/..........
My code is
My code is
insertIf i print the values they print last updated element ...........Code:#include <string.h>
#include <stdio.h>
typedef union
{
unsigned dd:4;
unsigned ee;
}ff;
typedef struct {
int unittype:2;
ff ss;
union {
int units:3;
} howmuch ;
//amount howmuch;
} product;
int main()
{
product dieselmotorbike;
product * myebaystore[2];
int nitems = 1; int i;
dieselmotorbike.unittype = 1;
dieselmotorbike.howmuch.units = 3;
dieselmotorbike.ss.dd = 14;
dieselmotorbike.ss.ee = 4;
myebaystore[0] = &dieselmotorbike;
for (i=0; i<nitems; i++) {
switch (myebaystore[i]->unittype) {
case 1:
printf("We have %u units for sale kg \n %u ",
myebaystore[i]->howmuch.units,
myebaystore[i]->ss.dd,
myebaystore[i]->ss.ee);
break;
case 2:
printf("We have %f kgs for sale\n",
myebaystore[i]->howmuch.units);
break;
}
}
}
[code
Please suggest the remedy..........
Sagar...
Not sure what you expect, but certainly this:
is one field, which you can either use as a 4-bit field or a (presumably) 32-bit. ee and dd will cover the same piece of memory (but of course dd is bigger, so it will cover some memory that is not covered by dd).Code:typedef union
{
unsigned dd:4;
unsigned ee;
}ff;
--
Mats
in the program if i assigned value to my dd and ee separetely they should print their own values but still they are giving last eneterd value..
What do you mean by
" ee and dd will cover the same piece of memory (but of course dd is bigger, so it will cover some memory that is not covered by dd). "
My turn to ask what you mean?
I mean that ee and dd overlap each other in the same location of memory.Quote:
What do you mean by
" ee and dd will cover the same piece of memory (but of course dd is bigger, so it will cover some memory that is not covered by dd). "
Consider this:
Now, x and y will have exactly the same memory address, and if we write this:Code:union a
{
int x;
int y;
};
This will produce 8 as the output.Code:union a aa;
...
aa.x = 7;
aa.y = 8;
printf("aa.x = %d\n", aa.x);
--
Mats