我教别人C语言编程简单的练习。
我无法获得strcmp()
功能工作。在C字符串比较提供分段错误
#include <stdio.h>
#include <string.h>
#define MAX 20
int main()
{
char s1[MAX], s2[MAX];
printf("Enter s1: ");
scanf("%s",s1);
printf("Enter s2: ");
scanf("%s",s2);
printf("S1 is %s\n",s1);
printf("S2 is %s\n",s2);
// string concatenation
strcat(s1,s2);
printf("S1 is %s\n",s1);
// string copy
strcpy(s1,s2);
printf("S1 is %s\n",s1);
// find the length of the string
int a = strlen(s1);
printf ("Length of S1 is %d\n", a);
int b = strlen(s2);
printf ("Length of S2 is %d\n", b);
// string comparison <<----- This is where it does not work
int c;
c = strcmp(s1, s2);
printf("C is %d\n",c);
if (c==0)
printf("S1 = S2\n");
else if (c<0)
printf("S1<S2\n");
else
printf("S1>S2\n");
return 0;
}
上述代码编译(带有警告)但不执行。它会抛出segmentation fault
错误并退出。 我用指针样式语法太多,但它在编译过程使我的错误。
作为一个方面说明,我看到很多人使用gets()
puts()
网站。但是当在我的程序中使用时,它告诉我使用上述函数已被弃用。如何确定可以使用哪些功能以及在哪里查找它们?
编辑
程序输出:
[email protected]:~/Documents/programs/C$ ./string Enter s1: test Enter s2: case S1 is test S2 is case S1 is testcase S1 is case Length of S1 is 4 Length of S2 is 4 C is 0 S1 = S2
这是我开始加入*
指针符号来试试,看看会有什么工作。
显示您的输入。 – BLUEPIXY
在显示的示例代码和输入中未唤醒段故障。 – BLUEPIXY
查看我的解释,为什么你的strcmp总是返回0. –