Search code examples
cstringsearchstrcmp

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


The program runs and exits with code 0, but gives no output, it's supposed to be a linear search program

I looked to other similar problems, i tried to end the array with \n. tried instead of just relying in just the "if (strcmp=0)" to make something with the values strcmp return, I'm very new and for what I'm learning not very good, just made things worst, i tried to look if it was about the char* values strcmp expect, but couldn't find the problem

#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);
}

The expected output would be element found in "i" position, if found if not found print "not found"


Solution

  • You want to pass it a string to find, not just one character Also, elementos should be a 2D array. Change the signature of your function to this:

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

    Also, in main, you don't call the function. Instead, you just declare it again. call it like this:

    lineal(elementos, elebus);
    

    Furthermore, I would change it to return void instead of int. You're neither returning anything (that's undefined behavior) nor are you using the return value anywhere. But I assume that this isn't the final version and you want to return the index at some point.


    On a side note, right now it's printing that it didn't find the element for every time it didn't match, even if it does find it eventually. I would recommend this instead:

    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
    

    This is printing "elemento no encontrado" only once, and only when the string wasn't found.