[英]String compare without using standard library function
I am new to C programming. 我是C编程新手。 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()
. 我正在尝试不使用标准函数来实现字符串比较。这里我使用了动态内存分配和
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 . fgets
的n
参数是缓冲区的大小, 包括null终止符 。 Thus, it reads up to at most n - 1
characters, and fills the last spot with a null-terminator. 因此,它最多读取
n - 1
字符,并用空终止符填充最后一个点。 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. 您对
getchar
第二次调用(在第一个fgets
)随后读取了最后一个字符, 而不是换行符,因此对fgets
的第二次调用提早停止,因为它立即命中了换行符。
Instead, you'll want to allocate n + 1
characters for each string, and call fgets
with n + 1
as well. 相反,您将需要为每个字符串分配
n + 1
字符,并同时调用n + 1
fgets
。
Also, you should check for malloc
failure before trying to write to s1
or s2
. 另外, 在尝试写入
s1
或s2
之前 ,应检查malloc
失败。
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. 从用户处获取后设置
n=n+1
。 This is to deal '\\0'
character 这是为了处理
'\\0'
字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.