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??
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With