这个 strcmp() 有什么问题?

what is wrong in this strcmp()?

我尝试用 strcmp() 编写简单的 C 函数。但我总是得到 Segmentation fault (core dumped)。怎么了?

char *arr={"abcdefg"};
char *a = arr[1];

if(strcmp(a, 'b') == 0)
{
    printf("it is b \n");
}

我认为这就是您一直在努力实现的目标:

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

int main(void)
{
    char *arr = {"abcdefg"};
    char a = arr[1];

    if( a == 'b' )
    {
        printf("it is b \n");
    }
}

What is wrong?

你没有让编译器帮助你自己。

在 GCC 上使用 -Wall -Wextra(这绝不是你能得到的最好的,而是你应该始终使用的最低限度),我得到:

testme.c: In function ‘main’:
testme.c:6:11: warning: initialization makes pointer from integer without a cast [enabled by default]
 char *a = arr[1];
           ^

您采用了 arr[1] —— 即 char'b' —— 将其转换为 char * .您的 a 现在指向地址 0x62 中的任何内容(假设为 ASCII),这绝对不是您想要的。您可能想要 &arr[1]arr + 1.

或者你想要一个char——那么你不应该声明char *,而strcmp()将是错误的首先使用。

testme.c:8:1: warning: passing argument 2 of ‘strcmp’ makes pointer from integer without a cast [enabled by default]
 if(strcmp(a, 'b') == 0)
 ^
In file included from testme.c:1:0:
/usr/include/string.h:144:12: note: expected ‘const char *’ but argument is of type ‘int’
 extern int strcmp (const char *__s1, const char *__s2)
            ^

strcmp() 需要两个 C 字符串 (char const *)。你的第二个参数 'b'int 类型......你可能想要 "b".

仍然不会比较相等,因为 "bcdefg" 不等于 "b"...

或者你想要一个单字符比较...那就是if ( a == 'b' )achar类型,而不是 char *(见上文)。

testme.c:10:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
     printf("it is b \n");
     ^
testme.c:10:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]

请帮我们张贴完整代码,包括int main()等等,这样我们就可以复制&粘贴&编译,而且还有行号匹配。

你在这里做错了很多事情。 strcmp 用于比较字符串。做你想做的最简单的方法是

char *arr= {"abcdefg"};
char a = arr[1];

if(a == 'b')
{
  printf("it is b \n");
}

如果您仍想使用 strcmp,您需要通过向其附加空终止符 [=15=] 来使 a 成为一个字符串。

char *arr= {"abcdefg"};
char a[] = {arr[1], '[=11=]'};

if(strcmp(a, "b") == 0)
{
  printf("it is b \n");
}