LearnFrenzy
Sign in Take a free test

C Input / Output · Find the Error · Question 1

Error: scanf("%d", n) without the & Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links