首页 > 解决方案 > 为什么 strlen() 没有返回正确的值?

问题描述

嗨,我很抱歉这是重复,但没有其他解决方案能够帮助我。变量 found 和 tofind 都是,"Point"但是当我调用时,strcmp我得到一个负数,当我打印它们的长度时,find 的长度为 9。有人可以帮我理解为什么会这样以及如何解决(如何让 found 和 tofind具有相同的值和长度)?太感谢了。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main(void) {
  char found[] = "";
  char tofind[] = "Point";


  int i = 0;

  while(i < 5){
    char f = tofind[i];


    strcat(found, &f);
    i++;

  }

  int r = strcmp(found, tofind);
  printf("%d\n", r);

  printf("Found: %s with len: %lu\n", found, strlen(found));//says len is 9

  printf("To Find: %s with len: %lu", tofind, strlen(tofind)); //says len is 5

return 0;
}

输出:

./main
-104
Found: Point with len: 9 this is i: 5
To Find: Point with len: 5

标签: arrayscstringlibraries

解决方案


推荐阅读