Question 1
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
int main(void) {
int n = 0;
scanf("%d", n);
printf("%d\n", n);
return 0;
}
- A %d should be %i
- B scanf receives the value of n (0) instead of its address, so it writes the number to an invalid address and the program crashes Correct
- C n must be initialised to 1
- D There is no bug
Correct Answer: Option B
scanf is variadic, so the compiler can only warn. At run time it treats 0 as a pointer and writes through it. Write scanf("%d", &n) and check that it returns 1.
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!