Comparison of char variables

1

I'm developing a program that needs to read a variable in char and compare it with another char . However, when performing comparisons using the strcmp(typed_pass, correct_pass) function, regardless of the text obtained through typed_pass , the result is valid, that is, return 0.

int main (int argc, char *argv[]) {

   char correct_pass[] = "test";
   char typed_pass[0];

   do {     
       printf ("\nTo unlock your last tip, enter the correct password: ");
       scanf ("%s", typed_pass);

   } while (strcmp(typed_pass, correct_pass));

   printf ("\nOK!");

   return;
}

I've already tried to do this with if and matrix position validations using a for , both of which were unsuccessful (using for me an error was returned).

Is there another way to do it or am I just wrong in creating the variables?

    
asked by anonymous 17.05.2017 / 03:51

1 answer

2

First, the comparison is being made with an array of characters. And you're comparing a size of 5 with a size of 0, of course that does not work, making the array of the correct size works, although you may still have some other problems.

#include <stdio.h>
#include <string.h>

int main (void) {
    char correct_pass[] = "test";
    char typed_pass[10];
    do {     
        printf ("\nTo unlock your last tip, enter the correct password: ");
        scanf ("%s", typed_pass);
    } while (strcmp(typed_pass, correct_pass));
    printf ("\nOK!");
}

See running on ideone . And on the Coding Ground. Also put it on GitHub for future reference .

You'd be better off with:

scanf ("%9s", typed_pass);

Actually scanf() is even discouraged, but for simple things like that it's ok.

    
17.05.2017 / 04:02