Reputation: 85
I am new to C programming. This is just a beginners question. I am trying to implement string compare without using standard function.Here i have used dynamic memory allocation and used fgets()
. But the second string is not inputted. Can anyone help me point out the problem? The code is given below.
#include <stdio.h>
#include <stdlib.h>
int my_strcmp(char*, char*);
int main()
{
int a, n;
printf("enter the length of strings\n");
scanf("%d",&n);
getchar();
char *s1 = (char *)malloc(n * sizeof(char));
printf("enter the string1\n");
fgets(s1, n, stdin);
getchar();
char *s2 = (char *)malloc(n * sizeof(char));
printf("enter the string2\n");
fgets(s2, n , stdin);
if (s1 == NULL)
{
printf("malloc error!!");
}
if (s2 == NULL)
{
printf("malloc error!!");
}
a = my_strcmp( s1, s2);
if (a == 0)
{
printf("the strings are equal");
}
else
{
printf("the strings are not equal");
}
free (s1);
free (s2);
return 0;
}
int my_strcmp( char *s1, char*s2)
{
while (*s1)
{
if (*s1 == *s2)
{
s1++;
s2++;
}
else
break;
}
if ( *s1 == *s2)
{
return 0;
}
else if (*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
}
Upvotes: 0
Views: 1520
Reputation: 11
I guess small changes should be used here: you can do like this:
...
do {
if (*s1 == '\0' || *s2 == '\0') {return 0;} // It's equal, and we've reached the end
} while (*s1++ == *s2++)
// This section will be executed only if difference found
return *s1 > *s2 ? 1 : -1 // shortcut to if statement, if condition is true, first statement will be used, if not, second.
Basically, it's more simple for program to execute, and takes less space, we don't need to check for equals/greaters as we already know, that if we've reached the end, and we are inside of the loop that checks equality, that totaly they are fully equal, and if we got out, that means there is some difference, and we just check if string is smaller or bigger, but i guess, much helpful would be returning index of difference, as it would tell much more info
Upvotes: 0
Reputation: 11706
The n
parameter of fgets
is the size of the buffer including null-terminator. Thus, it reads up to at most n - 1
characters, and fills the last spot with a null-terminator. Your second call to getchar
(after the first fgets
) then reads that last character, not the newline, so the second call to fgets
stops early because it immediately hits a newline.
Instead, you'll want to allocate n + 1
characters for each string, and call fgets
with n + 1
as well.
Also, you should check for malloc
failure before trying to write to s1
or s2
.
Upvotes: 3
Reputation: 1323
The code can be changed like this.
getchar(); //Fix
fgets(s1, n, stdin);
getchar();
char *s2 = (char *)malloc(n * sizeof(char));
Set n=n+1
after getting from user. This is to deal '\0'
character
Upvotes: 0