For the structure declaration below struct { char * a; short b; double c; char d
ID: 3582310 • Letter: F
Question
For the structure declaration below
struct {
char * a;
short b;
double c;
char d;
float e;
char f;
int g;
} foo;
the code is compiled for the cortex-m3, where the sizes of datatypes are as follows:
char 1
long 4
short 2
long long 8
int 4
double 8
float 4
any pointer 4
In addition, any datatype of size K must start at a K-byte boundary. The compiler will insert “padding” bytes to satisfy this rule.
(a) What are the byte offsets of all the fields in the structure?
(b) What is the total size of the structure?
(c) What is the total number of data bytes? of padding bytes?
(d) Rearrange the fields to minimize wasted space, and then show the byte offsets and total size for the rearranged structure.
Explanation / Answer
According to the condition of padding, structure would look like this.
struct {
char * a; //Character pointer size is of 4 bytes, Starts at byte 0 let say
short b; //Short size is 2 bytes, byte address of this element should be multiple of 2. This element start at byte 4
gap(2) //since double is of size 8, byte address should be multiple of 8
double c; //starts at byte 8
char d; //starts at byte 16
gap(3) //since double is of size 4, byte address should be multiple of 4
float e; //starts at byte 20
char f; //starts at byte 24
gap(3) //since int is of size 4, byte address should be multiple of 4
int g; //starts at byte 28
//Ends at byte 31
} foo;
Total size = 32 bytes
Padding bytes = 8 bytes
Data bytes = 24 bytes
Alternate approach without waste space
struct {
char * a; //Character pointer size is of 4 bytes, Starts at byte 0 let say
short b; //Short size is 2 bytes, byte address of this element should be multiple of 2. This element start at byte 4
char d; //starts at byte 6
char f; //starts at byte 7
double c; //starts at byte 8
float e; //starts at byte 16
int g; //starts at byte 20
//Ends at byte 23
} foo;
Total size = 24 bytes
Padding bytes = 0 bytes
Data bytes = 24 bytes
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.