Thanks..... Realy healpfull..
Originally posted by Banfa
No it doesn't, your implementation of C may provide a #pragma pack preprocessor directive but this is NOT standard C and many compilers do not provide this or any way to change structure alignment, you have to live with what ever it does. If your compiler has a #pragma pack and you use it then you will implicitly introduce an portability issue if the hardware of your project ever changes.
I am fully aware of the memory constraints that occur on smaller platforms (having programmed on a PIC with <4k RAM for the past year or so) the sizeof operator will give you the sizeof the type, if that type is a structure then it will include the padding (otherwise pointer arithmetic would not work properly).
Take this code for instance
[code=c]
struct MyStruct {
int i;
char c;
};
struct MyStruct mystruct;
int sms = sizeof mystruct;
int si = sizeof mystruct.i;
int sc = sizeof mystruct.c;
[/code]Assuming that the system has 4 byte (32 bit ints) and that it uses 4 byte alignment then once this runs
sms = 8;
si = 4;
sc = 1;
You can always find out how much wasted space there is in a structure on a given compiler/platform by comparing the sizeof the struct with the size of it's components, in this case 3 bytes (8 - (4+1)).
However it you use the rules I gave previously then wasted space will be minimised (typically 0-3 bytes per structure) on most platforms.
If you can not afford that wasted space don't use structures, although this will make the code more complex so you need to give the problem some careful thought before going down this route.
I am fully aware of the memory constraints that occur on smaller platforms (having programmed on a PIC with <4k RAM for the past year or so) the sizeof operator will give you the sizeof the type, if that type is a structure then it will include the padding (otherwise pointer arithmetic would not work properly).
Take this code for instance
[code=c]
struct MyStruct {
int i;
char c;
};
struct MyStruct mystruct;
int sms = sizeof mystruct;
int si = sizeof mystruct.i;
int sc = sizeof mystruct.c;
[/code]Assuming that the system has 4 byte (32 bit ints) and that it uses 4 byte alignment then once this runs
sms = 8;
si = 4;
sc = 1;
You can always find out how much wasted space there is in a structure on a given compiler/platform by comparing the sizeof the struct with the size of it's components, in this case 3 bytes (8 - (4+1)).
However it you use the rules I gave previously then wasted space will be minimised (typically 0-3 bytes per structure) on most platforms.
If you can not afford that wasted space don't use structures, although this will make the code more complex so you need to give the problem some careful thought before going down this route.
Comment