C 编程,为什么我不能将 strcpy() 与索引一起使用?



这是一个示例:

int main()
{
    char string1[8];
    char string2[7];
    strcpy(string1, "Heloooo");
    strcpy(string2, "Helloo");
    printf("%d", strcmp(string1[2], string2[5]));
    return(0);
}

即使它应该返回> 0、0、0或&&&&&&&&&&&&&&< 0。如果我删除索引,则喜欢:

    printf("%d", strcmp(string1, string2));

它可以正常工作。有人可以告诉我我在这里做错了什么?

strcmp采用一对角色指针,而 string1[x]不是指针,而是字符:

printf("%d", strcmp(&string1[2], &string2[5]));

printf("%d", strcmp(string1+2, string2+5));

请注意,尽管string1string2是数组,但C编译器将它们转换为字符指针,而无需其他操作员。

str [ndx]对char进行评估,但该功能期望char *,[] []产生l值,因此您可以获取其地址& str [ndx]并获取您的东西

函数 strcmp期望指示作为参数。请参阅原型:int strcmp(const char * s1, const char * s2);

string1[2]string2[5]只是字符'l''o'

printf("%d", strcmp(string1[2], string2[5])); // will not compile 
printf("%d", strcmp(&string1[2], &string2[5])); // will return -3 with my compiler GCC 5.3.0

&string1[2]string1[2]字符

的指针

&string2[5]string2[5]字符

的指针

注意:

strcmp()和strncmp()函数返回整数小于小于 等于S1(或第一个n字节)是等于或大于零 发现分别小于匹配或大于S2。

但是,确切的返回值取决于实现。

对于此实施:

int strcmp_fast (const char * s1, const char * s2)
{
    for(; *s1 == *s2; ++s1, ++s2)
        if(*s1 == 0)
            return 0;
    return *(const unsigned char *)s1 - *(const unsigned char *)s2;
}

printf("%d", strcmp_fast(&string1[2], &string2[5])); 

打印值是-3

最新更新