-1

I just started off on c and can't get this to work,

I tried to edit the code several times and even looked online for some examples but failed to understand how this would work.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
const char p1[10]="admin";
char p2[10];

printf("Password Required:");
scanf("%s", &p2)

if (p2==p1)
{
    printf("Access Granted")
}
else
{
    printf("Invalid Password")
}
}

It's meant to verify if the password entered is correct.

  • 1
    **Exact duplicate** of [How do I properly compare strings?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings) – selbie Sep 28 '19 at 04:01

1 Answers1

0

Your problem is on this line:

if (p2==p1)

You're comparing the memory addresses to see if they are equal, but NOT the contents stored at (i.e. pointed to in) them. To compare the passwords, instead use:

if (strcmp(p2, p1) == 0)

See: https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

MuffinMan
  • 889
  • 1
  • 8
  • 28
  • Yes, that would help me compare the total characters, but I'm not sure if it will see whether the characters match. – Ronson James Sep 28 '19 at 04:08
  • You need to read the article I posted - strcmp() doesn't compare the number of characters, it returns a value indicating equality: This function return values that are as follows − if Return value < 0 then it indicates str1 is less than str2. if Return value > 0 then it indicates str2 is less than str1. if Return value = 0 then it indicates str1 is equal to str2. Use strcmp and see if they are equal to 0. – MuffinMan Sep 28 '19 at 04:10
  • OK, thanks. Editing code rn – Ronson James Sep 28 '19 at 04:12
  • Improved the answer... – MuffinMan Sep 28 '19 at 04:13