Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why comparing strings in C doesn't work?

Tags:

c

I have the following program

main()
{

    char name[4] = "sara";
    char vname[4] = "sara";

    if(strcmp(name, vname) == 0)
    {
        printf("\nOK");
    }
    else
    {
        printf("\nError");
    }

}

This program always prints "Error"... what is the issue here help me

but if I change char vname[] = "sara", then it prints out "OK"... why??

like image 255
srisar Avatar asked Nov 28 '22 00:11

srisar


2 Answers

You are hard-sizing your arrays so that they are too short for the strings (they don't include an additional character for the null terminator). As a result, strcmp is running past the end of the strings when doing the comparison, producing essentially unpredictable results. You're lucky to not be getting a seg fault.

like image 77
Jollymorphic Avatar answered Jan 05 '23 01:01

Jollymorphic


Forgive me if this is off track, since I haven't done C in ages!

main()
{
    char name[] = "sara";
    char vname[] = "sara";

    if(strcmp(name, vname) == 0)
    {
        printf("\nOK");
    }
    else
    {
        printf("\nError");
    }
}

You've specified hard lengths for your char arrays, but in C, strings are null terminated, so "sara" actually needs len 5, not 4.

like image 27
Daryl Teo Avatar answered Jan 04 '23 23:01

Daryl Teo