2016-09-24 187 views
-3

我使用Pocket C++的ANSI C.我试图让strcmp()在我的计划工作:ANSI C:无法获取strcmp的工作

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

int main() 
{ 
    char str1 = 'C'; 
    char str2[3] = {'A', 'B', 'C'}; 
    int ret; 

    ret = strcmp(str1, str2[3]); 

    if (ret == 0) { 
     printf("The are equal"); 
    } else { 
     printf("They are not equal"); 
    } 

    return(0); 
} 

我得到了一个错误:

invalid conversion from 'char' to 'const char*' [-fpermissive]

以及其他错误。然后我尝试更改变量: char const * var = 'C';const char * var = 'C';

它仍然不起作用,我做错了什么?

+3

呦比较字符==就够了。 strcmp是用于字符串(它是char *并用分隔) –

+0

['int strcmp(const char * str1,const char * str2)'](http://www.cplusplus.com/reference/cstring/strcmp)期望2字符串('char'指针或'char *'),当你传递简单的'char'时 – CristiFati

+0

注意,'&str' **不足以作为char指针,因为[null termination]( https://en.wikipedia.org/wiki/Null-terminated_string)是必需的。 – Siguza

回答

1

what did I do wrong?

您发送错误的参数strcmp()功能而且你也是访问数组越界

我认为你对strcmp()函数的功能有误解。它不会比较两个字符,而是比较两个字符串(带有空终止字符的字符数组)。

如果你只是想比较两个字符串,然后不需要的功能,只需使用==操作是这样的:

ret = (str1 == str2[2]); 

if (ret == 1) 
{ 
    printf("The are equal"); 
} 
else 
{ 
    printf("They are not equal"); 
} 

所以,现在,时使用的strcmp()功能?

时,要比较这样两(与空终止字符结尾的字符数组)的字符串使用它:

char str1[10] = { 'a', 'b', 'c', '\0'}; 
char str2[10] = "abc"; //here automatically null character is provided at the end 
int ret; 

ret = strcmp(str1 ,str2); 

if (ret == 0) 
{ 
    printf("The are equal"); 
} 
else 
{ 
    printf("They are not equal"); 
}