in Programming edited by
214 views
3 votes
3 votes

Based on the struct alignment discussed in class,

What are the sizes of $\textsf{foo1, foo2, foo3}$ and $\textsf{foo4}$ respectively?

Sizes of primitive data types are given below.

sizeof(int) = 4 bytes
sizeof(short) = 2 bytes
sizeof(char) = 1 byte

struct foo1 {
    int d1;
    char c1;
    int d2;
};

struct foo2 {
    int d1;
    char c1;
    int d2;
    char c2;
    short s;
};

struct foo3 {
    int d1;
    int d2;
    char c1;
    char c2;
    short s;
};

struct foo4 {
    char c1;
    int d1;
    short s;
    int d2;
    char c2;
};
  1. $9,\; 12,\; 12,\; 12$
  2. $9,\; 12,\;16,\; 20$
  3. $12,\; 16,\; 12,\; 20$
  4. $12,\; 20,\; 20,\; 20$
in Programming edited by
214 views

1 Answer

2 votes
2 votes

Answer: C

Each variable of “type” must be stored at a location divisible by “sizeof(type)”.

Ints must be stored at locations 0, 4, 400, 256, 1024 etc.

chars can be stored anywhere since sizeof(char) = 1B and 1|anything.

To solve these types of questions first make a structure as wide as its largest sized element, then grow it in either upwards or downwards direction without altering the order of elements of structure.


int d1; char c1; int d2;
int d1: size 4B: location 0 – 3
char c1: size 1B: location 4 – 4 3B padded: location 5 – 7
int d2: size 4B: location 8 – 11

Width: 4B. Total size = 12B


int d1; char c1; int d2; char c2; short s;
int d1: size 4B: location 0 – 3
char c1: size 1B: location 4 – 4 3B padded: location 5 – 7
int d2: size 4B: location 8 – 11
char c2: size 1B: location 12 – 12

1B padded: location 13 – 13

short s: size 2B: location 14 – 15

Width: 4B. Total size = 16B


int d1; int d2; char c1; char c2; short s;
int d1: size 4B: location 0 – 3
int d2: size 4B: location 4 – 7
char c1: size 1B: location 8 – 8  char c2: size 1B: location 9 –   9 shot s: size 2B: location 10 – 11

Width: 4B. Total size = 12B


char c1; int d1; short s; int d2; char c2;
char c1: size 1B: location 0 – 0 3 bytes padded: location 1 – 3
int d1: size 4B: location 4 – 7
short s: size 2B: location 8 – 9 2 bytes padded: location 10 -11
int d2: size 4B: location 12 – 15
char c2: size 1B: location 16 – 16 3 bytes padded: location 17  – 19

Width: 4B. Total size = 20B

edited by

4 Comments

Nice explanation…

Just one minor correction needed in structure foo2.

Here, short s will not store at location 13-14, instead it will be stored at location 14-15 and 1B padded location will be 13-13.

 

1
1

Yes @ASNR1010 my bad, I have updated the answer. :)

0
0

beautiful presentation.

The main point of this question is : 

Each variable of “type” must be stored at a location divisible by “sizeof(type)”.

0
0
Answer:

Related questions