Tutorial :comparing strings



Question:

Considering this piece of code

char *pass="test";  int keyPressed;  char *password=(char *)malloc(PASS_LENGTH*sizeof(char));  int index=0;  printf("Enter the password please\n");  do  {      keyPressed=getch();      password[index++]=keyPressed;  }  while(keyPressed!=13);  int result=strcmp(pass,password);  

I think you understand what i want to do :)
I read in *password "test" but result is not 0, some explanation would be good:)


Solution:1

Since I think this is homework ... try writing out the strings after they've pressed Enter and see if you can see a difference.


Solution:2

You have to remove the last character and "close" the string: put

password[index - 1] = '\0'   

after the do-while.


Solution:3

akappa's suggestion will fix the strcmp problem you're seeing.

Also note you're mallocing a finite amount of memory but when writing this memory you don't check against the size of the allocated block. The code as written will allow writing passed the end of "password".


Solution:4

Looks like it would be "test\n" because you already added keyPressed. Thereby also overflowing the password variable.


Solution:5

You should malloc PASS_LENGTH+1 and set password[index] = 0 at before the last line of code. as strcmp and other C str routines work with ASCIIZ strings


Solution:6

The carriage return is included on the end of password.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »