C 线性搜索无法使用 strcmp 比较两个字符串,编译正常

C linear search failing to compare two strings using strcmp, compiles fine

程序运行并退出,代码为0,但没有输出,应该是线性搜索程序

我看了其他类似的问题,我试着用\n结束数组。尝试而不是仅仅依靠 "if (strcmp=0)" 来制作具有值 strcmp return 的东西,我是新手并且对于我所学的东西不是很好,只是让事情变得更糟,我试图查看是否与 strcmp 期望的 char* 值有关,但找不到问题

#include <stdio.h>
#include <string.h>
#define max 15

int lineal(char elementos[], char elebus)
{
    int i = 0;
    for(i=0; i<max; i++)
    {
        if(strcmp(elementos[i], elebus)==0)
        {
        printf("Elemento encontrado en %d,", i); //element found in
        }
    else 
        {
        printf("elemento no encontrado"); //not found
        }
    }

}

int main()
{
    char elebus[50];
    char elementos[max][50]= {"Panque", "Pastel", "Gelatina", "Leche", "Totis", "Tamarindo" "Papas", "Duraznos", "Cacahuates", "Flan", "Pan", "Yogurt", "Café", "Donas", "Waffles"};
    printf("Escribir elemento a buscar\n");
    scanf("%s", elebus);

    int lineal(char elementos[], char elebus);
}

预期输出将是在 "i" 位置找到的元素,如果找到的话 如果没有找到打印 "not found"

你想给它传递一个字符串来查找,而不仅仅是一个字符另外,elementos 应该是一个二维数组。将函数的签名更改为:

int lineal(char elementos[max][50], char *elebus)

此外,在 main 中,您不调用该函数。相反,您只需再次声明它。像这样称呼它:

lineal(elementos, elebus);

此外,我会将其更改为 return void 而不是 int。您既没有 returning 任何东西(这是未定义的行为),也没有在任何地方使用 return 值。但我假设这不是最终版本,你想 return 在某个时候索引。


附带说明一下,现在它正在打印每次不匹配时都找不到元素,即使它最终找到了它。我会推荐这个:

for (i = 0; i < max; i++)
    {
        if (strcmp(elementos[i], elebus) == 0)
        {
            printf("Elemento encontrado en %d\n,", i); //element found in
            return;
        }
    }
    printf("elemento no encontrado\n"); //not found

这仅打印一次 "elemento no encontrado",并且仅在未找到字符串时打印。