C字符串长度

rei*_*mos 0 c arrays string char

当我明确说明字符串的值,然后将其与自身进行比较时,系统返回FALSE.这是否与系统添加的额外'\ 0'字符有关?我应该如何优化我的代码使其成为正确的?

char name[5] = "hello";

if(name == "hello")
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

Sac*_*ith 5

您不能(有用)比较使用的字符串,!=或者==您需要使用strcmp它的原因是因为!=并且==只会比较这些字符串的基地址.不是字符串的内容.不要使用预定义的数组大小,char name[5] = "hello";而不是使用char name[] = "hello";char name[6] = "hello";使用时

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

int main()
{
char a[] = "hello"; 
char b[] = "hello";

   if (strcmp(a,b) == 0)
      printf("strings are equal.\n");
   else
      printf("strings are not equal.\n");

   return 0;
}
Run Code Online (Sandbox Code Playgroud)