For unknown reason, result of running my C program is quite unexpected. I think that it has to be some kind of a beginner mistake, however I can't find out really, where is it.
#include <stdio.h>
#include <string.h>
int main()
{
char string1[50];
char string2[50];
int compare;
puts("Enter two strings: ");
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);
compare=strcmp(string1, string2); /* usage of extra variable makes the code more readable but wastes more memory */
printf("%d: ",compare);
if (compare<0) puts("First string is lesser");
else if (compare>0) puts ("First string is bigger");
else puts("Strings are equal");
return 0;
}
And on testing:
Enter two strings:
heheisntthisalongstring
heheisntthisalongstring
1: First string is bigger
------------------
(program exited with code: 0)
Press return to continue
Shouldn't those strings be equal?
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);
These are wrong. string1
and string2
are not initialized, and strlen
just counts the number of bytes, till hitting \0
. In this case, strlen
could return any (random non-negative) number.
Use sizeof
, instead of strlen
here.
Here
char string1[50];
char string2[50];
you dont initialise them, so your initial calls to strlen
are unreliable as they are looking for the first null char they find after the start of the array. This could be anywhere and the results of the call may or may not be a true reflection on the size - you just cant rely at all on the results.
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