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;
}
}
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
.