我是C编程新手。这只是一个初学者的问题。我试图在不使用标准函数的情况下实现字符串比较。这里我使用了动态内存分配并使用了fgets()
。但是没有输入第二个字符串。任何人都可以帮我指出问题吗?代码如下。
#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;
}
}
答案 0 :(得分:2)
n
fgets
参数是缓冲区的大小,包括null-terminator 。因此,它最多读取n - 1
个字符,并使用空终止符填充最后一个点。第二次调用getchar
(在第一个fgets
之后)然后读取最后一个字符,不换行符,因此第二次调用fgets
会提前停止,因为它立即点击换行符。
相反,您希望为每个字符串分配n + 1
个字符,并使用fgets
调用n + 1
。
此外,您应该在尝试写入malloc
或s1
之前检查s2
失败。
答案 1 :(得分:0)
代码可以这样改变。
getchar(); //Fix
fgets(s1, n, stdin);
getchar();
char *s2 = (char *)malloc(n * sizeof(char));
从用户获取后设置n=n+1
。这是为了处理'\0'
字符