samedi 18 mai 2019

C: Flaw when checking if a character in the string is NULL

I have a problem while checking if a specific character in my string is NULL ('\0'). It gives me false positives, or I think so.

In my code I want to know if somebody inputted more than 3 or less than 2 characters.

I have tried putting NULL instead of '\0' and it still does give me false positives.

This is what I did to check:

int main(){
   char* str = (char*) calloc(10,sizeof(char));
   scanf("%s",str);
   if (str[1]=='\0' || str[3]!='\0') printf("Test");

   return 0;
}

It gives the right output ("Test") when my input is more than 3 characters or less than 2 characters, but does also give me false output of ("Test") when it is 2 characters. It only works as usual when it is exactly 3 characters. I want to make it work (not output "Test") with 2 or 3 characters.

Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire