Comparison of char type variables

Asked

Viewed 738 times

1

I’m developing a program that needs to read a variable in char and compare the same with another char. However, when performing the comparisons using the function strcmp(typed_pass, correct_pass), independent of the text obtained through typed_pass, the result is valid, ie 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 have already tried to carry out this operation through if and validations by matrix position using a for, both unsuccessful (using the for an error has been returned to me).

Is there another way to do it or am I just missing in the creation of variables?

  • 1

    It is correct to set the variable typed_pass size 0?

  • I figured by setting the size to 0, the character allocation space would become dynamic.

1 answer

2


First, the comparison is being made with a array of characters. And is comparing a size 5 to a size 0, of course this does not work, making the array 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!");
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Would be better with:

scanf ("%9s", typed_pass);

In fact the scanf() it is even disincentivated, but for simple things like this it is ok.

  • 1

    bigown, why the character array would have size 5 containing the text test? I vaguely remember studying in college about character \0 finalizing a string. That would be the reason?

  • 2

    @Andersoncarloswoss that’s right https://answall.com/q/177619/101

  • You mentioned that there may still be other problems. Can you show me a better way to write this code?

  • 1

    @Drythz The main thing that’s worth talking about right now, while you’re learning is that the scanf() can read more than 10 characters.

  • 1

    @Drythz and, following what the bigown said, it is good to create the habit of using the specifier %9s instead of %s when a 10-character array is being passed for reading, %31s when passing a 32 position vector, etc. This avoids a whole class of problems called buffer overflow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.