Matt wanted to flex his C programming skills by playing with structs and unions.
ID: 3597513 • Letter: M
Question
Matt wanted to flex his C programming skills by playing with structs and unions. He devised the following code.
A. What is the output of the two print statements in lines 38 and 42? Explain this result.
B. In part A, if the expected result differed from the actual result, how might you change the existing code to work as intended?
C. Show the partitioning of the bar_t struct (i.e., show the number of bytes dedicated to each field).
D. How many bytes does the bar_t struct require in total?
5 typedef union foo short * long long int y char z 10 foo_t 12 typedef struct bar 13 14 foo t foo stuffs [3]: char msg [64] bar t 16 17 18 Void do somethingl (bar t a bar) 19 20 21 strcpy a bar msg, "do somethingi did something") 23 bar t dosomething2 (void) 24 25 26 27 28 29 30 void main (int argc, char argv [l) 31 E 32 bar t bar strcpy bar msg, "do_something2 did something!") return &bar; bar t fun = (bar t ) malloc(1 * size of (bar t)); strcpy fun-msg, "If only something would happen." 34 35 36 // do somethingl do something1 (fun) print f I "do. Something! result: s ", fun- msg); 38 39 40 41 // d some thing2 fun do_something2) printf("do somethina2 result: %s ", fun -msg) ; 43Explanation / Answer
A.
output of print statement at 38 : do something1 result if only something whould happen!
explanation: fun is a local struct variable. so, eventhough the function
void do_something1(bar_t a_bar)
{
strcpy(a_bar.msg, "do_something1 did something!");
}
changes the value of a_bar.msg it is not reflected back in the fun struct. also the function is not returning any value. hence the value printed is of the struct fun from main function.
output of print statement at 42 : no output - error with return value from do_something2()
B. So as to get the second print statment executed changing do_something() and the fucntion call like given below will help.
bar_t do_something2(void)
{
bar_t bar;
strcpy(bar.msg,"do_something2 did something!");
return bar;
}
bar_t funn = do_something2();
printf("do something2 result %s ", funn.msg);