我有以下代码。我从 http://www.gnu.org/software/libc/manual/html_node/crypt.html 拿来的
#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <crypt.h>
int
main(void)
{
/* Hashed form of "GNU libc manual". */
const char *const pass = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/";
char *result;
int ok;
printf("%s\n",pass);
/* Read in the user’s password and encrypt it,
passing the expected password in as the salt. */
result = crypt(getpass("Password:"), pass);
printf("%s\n",result); /*I added this printf*/
/* Test the result. */
ok = strcmp (result, pass) == 0;
printf("valor de la comparacion: %i\n",ok);/*I added it*/
puts(ok ? "Access granted." : "Access denied.");
return ok ? 0 : 1;
}
当我键入 GNU libc manual 时,输出为“已授予访问权限”。但是 strcmp 返回的值为 1,这个值意味着 result 和 pass 不相等。但是输出是:
$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
Password:
$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
valor de la comparacion: 1
Access granted.
我对 strcmp 的行为很困惑。
最佳答案
您正在打印 ok
的值。
在这一行:
ok = strcmp (result, pass) == 0;
它将strcmp
的返回值与0
进行比较。它们是相等的,所以比较是正确的。这会将 ok
设置为 1
。将整数设置为 bool 比较的结果,为真提供 1
,为假提供 0
。
关于c - 当 2 个字符串相等时,strcmp 返回 1,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965447/