Why doesn't string comparison in C work?

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 problem? help me

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

+4
source share
4 answers

You rigorously tune your arrays to be too short for strings (they do not include an extra character for the null terminator). As a result, strcmp works beyond the end of the lines when performing comparisons, creating almost unpredictable results. You are fortunate that you will not get a seg error.

+19
source

Forgive me if this does not work, because I did not do C in age!

 main() { char name[] = "sara"; char vname[] = "sara"; if(strcmp(name, vname) == 0) { printf("\nOK"); } else { printf("\nError"); } } 

You specified hard lengths for char arrays, but strings have zero termination in C, so "sara" actually requires len 5, not 4.

+8
source

Because name and vname do not contain strings. By specifying a size of 4 for each of them, with a 4-character string as initializer, you told the compiler to save only those 4 characters without the '\0' null character that marks the end of the string.

Undefined behavior; you are (un) lucky this is not just a glitch.

Delete 4 (or change it to 5 ):

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

EDIT . Here is a modified version of your program that fixes a number of other problems (see comments). Other that omits 4 in the name and vname , most of the changes are not directly related 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 */ } 
+7
source

This is because you do not allocate enough space for your lines (4 bytes can store the characters "sara", but not the null character at the end of the line.

strcmp looks at the line until it reaches the nul character or the difference in the lines, and then if it reaches zero for both lines, they are equal. Since you are not allocating arrays large enough for the null character, you will get two strings unequal. In fact, on most systems you will probably get a name that will look like "sarasara", and vname will just be "sara", since vname appears immediately after the name, there is a good chance that it will be stored in memory and overwritten the nul char names .

+1
source

All Articles