Tutorial :comparing strings


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:)


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


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

password[index - 1] = '\0'   

after the do-while.


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".


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


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


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
Next Post »