A compound literal (int[]){1, 2, 3} appears inside a function body in C99. What is its storage duration?
Correct answer
B. Automatic, matching the enclosing block, so the array dies when that block exits
15 views
B. Automatic, matching the enclosing block, so the array dies when that block exits
15 views
Compound literals inside a block have automatic storage duration tied to that block, so returning (int[]){1,2,3} hands back a dangling pointer. At file scope the same syntax creates an object with static storage duration, which is why initialising a global pointer from a compound literal works. The trap is subtle because the literal looks like a constant expression.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.