2016-05-18 90 views
-2

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

這是我開始加入*指針符號來試試,看看會有什麼工作。

+2

顯示您的輸入。 – BLUEPIXY

+0

在顯示的示例代碼和輸入中未喚醒段故障。 – BLUEPIXY

+0

查看我的解釋,爲什麼你的strcmp總是返回0. –

回答

2

剛卸下線指針:

printf("S1 is %s\n",*s1); 
printf("S2 is %s\n",*s2); 

是這樣的:

printf("S1 is %s\n",s1); 
printf("S2 is %s\n",s2); 

要知道更多關於C指針,也有很多的教程在互聯網上,類似這樣的一個:http://karwin.blogspot.com.br/2012/11/c-pointers-explained-really.html

要了解更多關於c和C++函數的信息,可以參考他們的官方文檔,在此鏈接中:http://en.cppreference.com/w/

編輯: 在這條線,你作出的strcat:

strcat(s1,s2) 

所以S1將有S1 + S2的值,但對下一行,你正在做的一個副本s2進入s1。

strcpy(s1,s2) 

之後,s1將具有與s2相同的值,因此s1現在等於s2。這就是爲什麼你的strcmp總是返回0.你可以看到發生在你的輸出。

S1 is test  #S1 initialy 
S2 is case  #S2 initialy 
S1 is testcase #S1 after strcat(s1,s2) 
S1 is case  #S1 after strcpy(s1,s2) 

正如你可以看到S1到底有相同的值S2。

這應該工作:)

2

您使用scanf不正確。我懷疑你的程序的狀態正在通話損壞到scanf但它沒有被發現,直到你打電話strcmp

當使用scanf讀取標準輸入到一個字符串,使用以下格式:

#define LENGTH 20 
char str[LENGTH+1] = {0}; 
scanf("%20s", str); // note the "max-length" format parameter of 20. 

通過使用地址的運營商(&)這意味着scanf將寫入由值定義的地址傳入,因爲您沒有爲s1值設置初始值,所以程序的行爲未定義。

更安全,可以考慮使用格式字符串的LENGTH define'd價值,所以不重複的20值:

scanf("%" #LENGTH "s", str) 
+2

'#define LENGTH 20;' - >'#define LENGTH 20','char str [LENGTH];' - >'char str [LENGTH + 1];' ,'scanf(「%」#LENGTH「s」)'不好。 – BLUEPIXY

+0

@BLUEPIXY謝謝 - 我解決了前兩個問題(並清除了'str'數組),但是我使用'scanf'出了什麼問題? – Dai

+0

嘗試編譯它。 – BLUEPIXY

1

scanf的第二個參數是應該有一個地址,這是s1s2。將其更改爲:

scanf("%s", s1); 
scanf("%s", s2); 
+0

爲什麼我們應該跳過這個'scanf'中的'&'符號? – Prasanna

+1

@Prasanna對於普通的'int x;','&x'是它的地址。對於數組char'[MAXN];','s'本身就是字符串的起始地址。 – delta