简体   繁体   中英

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

因为我认为这是作业...尝试在按下Enter后写出字符串,看看你是否能看到差异。

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

回车包含在password的末尾。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM