Question 10
Back to Exercise
What is the output of the following C program?
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
int x = *(const int *) a, y = *(const int *) b;
return (x > y) - (x < y);
}
int main(void) {
int sorted[] = {2, 4, 8, 16, 32, 64};
int k1 = 16, k2 = 10;
int *p = bsearch(&k1, sorted, 6, sizeof(int), cmp);
int *q = bsearch(&k2, sorted, 6, sizeof(int), cmp);
printf("%td %d\n", p - sorted, q == NULL);
return 0;
}
- A 3 1 Correct
- B 4 1
- C 3 0
- D 16 1
Correct Answer: Option A
bsearch returns a pointer to the matching element (index 3) or NULL when the key is absent. The array must be sorted with the same comparator.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!