简体   繁体   English

当2个字符串相等时,strcmp返回1,为什么呢?

[英]strcmp returns 1 when 2 strings are equal, Why?

I have the following code. 我有以下代码。 I took it from http://www.gnu.org/software/libc/manual/html_node/crypt.html 我从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;
}

When I type GNU libc manual the output is "Acces granted". 当我输入GNU libc manual时,输出为“ Acces grant”。 but the value returned by strcmp is 1 and this value means that result and pass are not equal. 但是strcmp返回的值为1,该值表示结果和传递不相等。 However the output is : 但是输出是:

$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
Password:
$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/
valor de la comparacion: 1
Access granted.

I am very confused about behavior of strcmp. 我对strcmp的行为非常困惑。

You are printing the value of ok . 您正在打印ok的值。

On this line: 在这行上:

ok = strcmp (result, pass) == 0;

it compares the return value of strcmp to 0 . 它将strcmp的返回值与0进行比较。 They are equal, so the comparison is true. 它们是相等的,因此比较是正确的。 That sets ok to 1 . ok设置为1 Setting an integer to the result of a boolean comparison gives 1 for true, and 0 for false. 将一个整数设置为布尔比较的结果时,将1为true,将0为false。

but the value returned by strcmp is 1 and this value means that result and pass are not equal 但是strcmp返回的值为1,并且该值表示结果和传递不相等

You are mistaken. 你误会了。 In c, the value 1 is synonymous with true and false is 0. 在c中,值1等于truefalse为0。

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("%i\n", 1 == 2);
    printf("%i\n", 1 == 1);
}

Output is 输出是

0
1

The assignment operator = has lower precedence than the relational operator == . 赋值运算符=优先级低于关系运算符==优先级。 So the statement ok = strcmp (result, pass) == 0; 因此,语句ok = strcmp (result, pass) == 0; is equivalent to ok = (strcmp (result, pass) == 0); 等价于ok = (strcmp (result, pass) == 0); . You are not assigning the result of strcmp to ok , but the result of strcmp (result, pass) == 0 . 没有strcmp的结果分配给ok ,而是将strcmp (result, pass) == 0的结果strcmp (result, pass) == 0分配了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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