Reputation: 1571
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??
Upvotes: 5
Views: 11000
Reputation: 263217
Because name
and vname
don't contain strings. By specifying a size of 4 for each of them, with a 4-character string as the initializer, you've told the compiler to store just those 4 characters without the '\0'
null character that marks the end of the string.
The behavior is undefined; you're (un)lucky that it didn't just crash.
Remove the 4
(or change it to 5
):
char name[] = "sara";
char vname[] = "sara";
EDIT: Here's a modified version of your program that fixes several other issues (see comments). Other that omitting the 4
on the declarations of name
and vname
, most of the changes are not directly relevant to your question.
#include <stdio.h> /* needed for printf */
#include <string.h> /* needed for strcmp */
int main(void) /* correct declaration of "main" */
{
char name[] = "sara"; /* omit 4 */
char vname[] = "sara"; /* omit 4 */
if (strcmp(name, vname) == 0)
{
printf("OK\n"); /* \n is at the *end* of the line */
}
else
{
printf("Error\n"); /* as above */
}
return 0; /* not absolutely required, but good style */
}
Upvotes: 9
Reputation: 141839
It's because you're not allocating enough space for your strings (4 bytes can store the characters of "sara", but not the nul character at the end of the string.
strcmp
walks through the string until it reaches a nul character, or a difference in the strings and then, if it reached a nul for both strings they are equal. Since you don't allocate arrays large enough for a nul character you'll end up with your two strings being unequal. In fact in most systems you'll probably get name being something like "sarasara" and vname being just "sara", since vname comes right after name, there is a good chance it will be stored their in memory and overwrite names nul char.
Upvotes: 1
Reputation: 5495
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.
Upvotes: 10
Reputation: 3530
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.
Upvotes: 21