我教別人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. –