ProgrammingVery hardProduct-company MCQ pattern
What is printed? (This program has no undefined behavior.)
What is printed? (This program has no undefined behavior.)
char *fmt(int n) {
static char buf[16];
sprintf(buf, "%d", n);
return buf;
}
int main(void) {
char *arr[3];
for (int i = 0; i < 3; i++) arr[i] = fmt(i * 10);
printf("%s %s %s", arr[0], arr[1], arr[2]);
}- A. Undefined behavior: garbage values
- B. 0 10 20
- C. 0 0 0
- D. 20 20 20
Correct answer: D. 20 20 20
All three pointers in arr alias the SAME static buf, which gets overwritten on every call. By the time printf runs, buf holds "20" (the last call's result), so all three %s conversions read that same final content — well-defined, just logically wrong.
More C Programming questions
- What is printed? Assume a 64-bit LP64 ABI (4-byte int). c int a[3][2] = {{1,2},{3,4},{5,6}}; int (p)[2] = a; p = p + 2; printf("%ld %d"…
- Which statement about this code is correct? c int add(int a, int b) { return a + b; } int main(void) { int (fp)(int) = (int ()(int))add…
- What is printed? c int a[3] = {1,2,3}; int parr[3] = {a, a+1, a+2}; int pp = parr; (pp + 1) += 10; printf("%d %d %d", a[0], a[1], a[2]);
- What is printed? c typedef int (Op)(int,int); int a(int x,int y){ return x+y; } int b(int x,int y){ return x-y; } Op table[2] = {a, b}…
- What is printed? c int a[2][3] = {{1,2,3},{4,5,6}}; int rowptrs[2] = {a[0], a[1]}; int pp = rowptrs; for (int i = 0; i < 2; i++) for (int…
- Assume a 64-bit LP64 ABI (4-byte int, 8-byte pointers, natural alignment). What is printed? c struct Inner { char a; short b; }; struct…