LearnFrenzy
Sign in Take a free test

C Library Functions · Find the Error · Question 7

Error: comparing strings with == Answer, explanation & discussion

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

This program prints "access denied" although the input is "admin". Why?

main.c
#include <stdio.h>

int main(void) {
    char role[16] = "admin";
    if (role == "admin")
        puts("welcome");
    else
        puts("access denied");
    return 0;
}
  • A role is too long
  • B == compares the addresses of the array and the literal, not their characters; use strcmp(role, "admin") == 0 Correct
  • C puts needs a newline
  • D There is no bug
Correct Answer: Option B

An array and a string literal are different objects, so their addresses are never equal. strcmp from <string.h> compares the contents.

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