ProgrammingHardProduct company OA
What is printed?
What is printed?
struct Shape { int w, h; int (*area)(struct Shape *); };
int rect(struct Shape *s) { return s->w * s->h; }
int tri(struct Shape *s) { return s->w * s->h / 2; }
int main(void) {
struct Shape a[] = {{3, 4, rect}, {3, 5, tri}, {2, 2, rect}};
int t = 0;
for (int i = 0; i < 3; i++) t += a[i].area(&a[i]);
printf("%d", t);
}- A. 22
- B. 24
- C. 23
- D. 31
Correct answer: C. 23
Each struct carries its own function pointer, a hand-made version of virtual dispatch. rect gives 12 and 4; tri gives 15 / 2 = 7 in integer division. 12 + 7 + 4 = 23. '24' rounds 7.5 up; '31' treats every shape as a rectangle.
More C Programming questions
- What is printed? c int i = 0, s = 0; top: s += i; if (++i < 5) goto top; printf("%d %d", s, i);
- What is printed? c int calls = 0; int mx(int a, int lo, int hi) { calls++; if (lo == hi) return a[lo]; int m = (lo + hi) / 2; int l =…
- What is printed? c int a[] = {1, 2, 3}, p = a; int x = ++p++; int y = p++ 10; printf("%d %d %d %d", x, y, a[0], p);
- What is printed? c int x = 10; int p = &x, pp = &p; printf("%d", pp + p 2);
- What is printed? c const char s = " 42, 17"; printf("%zu %zu", strspn(s, " "), strcspn(s, ","));
- A header config.h is wrapped as #ifndef CONFIGH / #define CONFIGH / … / #endif. What problem does this prevent?