ProgrammingVery hardProduct company OA
What is printed?
What is printed?
int *slot(int i) { static int box[3]; return &box[i % 3]; }
int main(void) {
*slot(0) = 5;
*slot(4) = 7;
int *p = slot(3);
*p += *slot(1);
p[2]--;
printf("%d %d %d", *slot(0), *slot(1), *slot(2));
}- A. 5 7 0
- B. 12 7 0
- C. 12 7 -1
- D. 5 12 -1
Correct answer: C. 12 7 -1
box has static storage: it is zero-initialised, exists for the whole program and every call returns a pointer into the same array, so returning its address is safe (unlike an automatic local). slot(4) is box[1] = 7 and slot(3) is box[0], so *p += 7 makes box[0] = 12; p[2] is box[2], decremented from 0 to −1. '5 7 0' treats each call as getting a fresh array.
More C Programming questions
- What is printed? c #define A 1 #define B #if defined(B) && A + C #define X 10 #else #define X 20 #endif #undef A #ifdef A #define Y 1…
- An array of int that may contain any values from INTMIN to INTMAX is sorted with qsort. With int x = (const int )a, y = (const int )b…
- What is printed? c int a[] = {4, 8, 15, 16, 23}; printf("%zu %d", sizeof(a) / sizeof(a[0]), a[sizeof(a) / sizeof(a[0]) - 1]);
- What is printed? c printf("%d %d %d", 5 > 3 && 2 > 4, !0, !!7);
- What is printed? c int a = 5, b = 3; a = a ^ b; b = a ^ b; a = a ^ b; printf("%d %d", a, b);
- What is printed? c printf("%d %d %d", strcmp("abc", "abd") < 0, strcmp("ab", "abc") < 0, strncmp("abcx", "abcy", 3) == 0);