比较 C 中的字符会引发错误

标签 c arrays pointers char

我是 C 语言新手,作为练习,我正在创建库来处理字符串。

现在我正在创建一个名为“indexOf”的函数,它返回字符串中放置字符的索引。

ma​​in.c(阅读代码注释以获取有关错误的信息)

#include <stdio.h>
#include <stdlib.h>
#include "jstring.h"

int main()
{
    char name[] = "Juan";
    printf("The char 'a' is in the index %d \n\n", indexOf(name, 'a'));

    return 0;
}

jstring.h

#include <string.h>

int indexOf(char haystack[], char needle)
{
    int index = 0;
    while(haystack[index] != '\0')
    {
        //Prints char by char untill the needle is found (for testing)
        printf("%c\n", haystack[index]);

        if(strcmp(haystack[index], needle) == 0) //Causes error (app strops working)
        {
            printf("Needle found!");
            return index;
        }
        index++;
    }
    return -1;
}

如果我使用下一个代码,它就不起作用

if(haystack[index] == needle) //Is never true
{
     printf("Needle found!");
     return index;
}

知道名字是“Juan”的程序应该返回 2 作为字符“a”位置的索引。我不知道这段代码有什么问题,我已经习惯了指针,也许与此有关。

我搜索了很多有关比较字符的 StackOverflow 问题,但没有找到最终不使用 strcmp() 或与我的函数具有相似目标的问题。

最佳答案

首先你不能使用

if(strcmp(haystack[index], needle) == 0)

因为 needle 不是以 null 结尾的字符串。 haystack[index] 都不是。要在 strcmp 中使用 haystack[index],您必须使用 &haystack[index]

其次,您的代码使用简单的 == 效果很好

int indexOf(char haystack[], char needle)
{
    int index = 0;
    while(haystack[index] != '\0')
    {
        //Prints char by char untill the needle is found (for testing)
        printf("%c\n", haystack[index]);

        if(haystack[index] == needle ) 
        {
            printf("Needle found!\n");
            return index;
        }
        index++;
    }
    return -1;
}
int main()
{
    char name[] = "Juan";
    printf("The char 'a' is in the index %d \n\n", indexOf(name, 'a'));

    return 0;
}

关于比较 C 中的字符会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33887366/

相关文章:

c++ - 使用哪种语言来实现一些 Linux shell 命令(作业)——纯 C 还是 C++?

在 fork() 和 exec() 之后创建管道

arrays - 在 PowerShell 中将数组追加到数组数组

c++ - 变长数组作为 C++ 中的函数输入

arrays - 为什么不能在 Go 中将 [Size]byte 转换为字符串?

C 表示法 : pointer to array of chars (string)

c - "producing negative zeroes"在不支持的系统中是什么意思?

在 FreeRTOS 中创建具有多个队列的任务?

c++ - 如何通过在 Arduino 中引用我的类来传递串行对象?

c - 减去指针 : how variable j is getting this value?