Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Give the minimum size of each of the following C data structures, assuming that

ID: 3859774 • Letter: G

Question

Give the minimum size of each of the following C data structures, assuming that char values occupy byte, int and float values occupy four bytes, double values occupy eight bytes, and pointers occupy bytes. (a) char str[] = "Curly": (b) double *a[4][4]: (c) char *str[3] = {"Moe", "Larry", "Curly"}: (Include the space occupied by the string literals in your answer.) (d) union { int a: char b: float c[4]: }u: (e) struct { int a: char b: float c[4]: }s: (f) union { int a[3]: double b: struct { float c: char d[4]: }s: }u: (g) struct { float a: union { double b[2]: int c: }u: char d: }s;

Explanation / Answer

In c there is a method sizeof which helps you calculate the number of bytes.

eg :

#include <stdio.h>

int main()
{
char str[] = "Curly";
printf("Size of %d bytes ",sizeof(str));

return 0;
}

Output :

6 bytes.

a) char str[] = "Curly";

Assuming char as 1 byte : size is 6 bytes

b) double *a[4][4];

size of double is 8

size of a is 16*8 = 128 bytes

c) char *str[3] = {"Moe", "Larry", "Curly"};

(Include the space occupied by the string literals in your answer.)

char * str occupies 8 bytes.

str[3]

8*3 = 24 bytes.

D) union {

int a;

char b;

float c[4];

} u;

In union, considers only the datatype with highest number of bytes : sizeof c is 4*4 = 16 bytes.

e) struct {

int a;

char b;

float c[4];

} s;


sum of all variables : 4+1+ (4*4) = 21 bytes.

f) union {

int a[3];

double b;

struct {

float c;

char d[4];

} s;

} u;


In the above example the total size of u is the size of u.s (which happens to be the sum of the sizes of u.s.u and u.s.d), since s is larger than both i and f. When assigning something to u.i, some parts of u.f may be preserved if u.i is smaller than u.f.

Reading from a union member is not the same as casting since the value of the member is not converted, but merely read.

Total size = 16 bytes

g) struct {

float a;

union {

double b[2];

int c;

} u;

char d;

} s;


Total size is 32 bytes.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote