Question 7
Back to Exercise
This program prints "access denied" although the input is "admin". Why?
#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!