被strcmp困惑

Erw*_*inM 2 c string strcmp

我有一个非常简单的函数来将表示位串的3字符串转换为十进制数:

int bin3_to_dec(char *bin) {
  int result;

  result=0;
  printf("string: %s\n", bin);
  printf("c0: %c\n", bin[0]);
  printf("c1: %c\n", bin[1]);
  printf("c2: %c\n", bin[2]);

  if ((strcmp(&bin[0], "1") == 0))
    result += 4;
  if ((strcmp(&bin[1], "1") == 0))
    result += 2;
  if ((strcmp(&bin[2], "1") == 0))
    result += 1;
  printf("result: %d\n", result);
  return result;
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序并为此函数提供111它应该计算的字符串时7.而不是它输出:

string: 111
c0: 1
c1: 1
c2: 1
result: 1
Run Code Online (Sandbox Code Playgroud)

为什么不计算正确的值?为什么只有第三个条件顺利通过?

438*_*427 5

你的字符串bin等于"111"实际上由四个字符组成 - 即'1','1','1','\ 0',其中第四个字符的值为零,终止(即结束)字符串.

&bin[0]字符串也是如此"111"

并且&bin[1]是字符串"11"

并且&bin[2]是字符串"1"

那么你的代码实际上做的是:

  if ((strcmp("111", "1") == 0))
    result += 4;
  if ((strcmp("11", "1") == 0))
    result += 2;
  if ((strcmp("1", "1") == 0))
    result += 1;
Run Code Online (Sandbox Code Playgroud)

只有最后一次比较结果为真,所以result变为1