The program below has a bug. Which statement correctly describes it?
main.c
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main(void) {
int ops[2](int, int) = {add, sub};
printf("%d\n", ops[0](2, 3));
return 0;
}
AThe functions must be static
BArrays of functions do not exist; it must be an array of function pointers: int (*ops[2])(int, int)
Cops needs a size of 3
DThere is no bug
Correct Answer: Option B
Functions are not objects, so they cannot be array elements. Pointers to them can.
The program below has a bug. Which statement correctly describes it?
main.c
#include <stdio.h>
double half(double x) { return x / 2; }
int main(void) {
int (*fp)(int) = half;
printf("%d\n", fp(9));
return 0;
}
Ahalf must be static
Bfp points to functions (int) returning int, but half takes and returns double – the function pointer types are incompatible
Cfp(9) needs a cast
DThere is no bug
Correct Answer: Option B
Calling a function through a pointer of a different type is undefined behaviour, so compilers reject the assignment. Declare double (*fp)(double) = half;.
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·