2017-02-03 177 views
-2

這段代碼工作正常。但我想知道是否可以以更有效的方式完成?函數指針C

更具體地說,這部分*(s1 + i)如果有可能強制它通過指針例如*s1++指針整個數組字符。 我的任務是做這個函數compareStrings沒有索引數組[]。

int compareStrings(const char *s1, const char *s2) 
{ 
    int i = 0, answer; 
    // i - to sequence through array of characters 
    // pointer to character string1 and character string2 
    while (*(s1 + i) == *s2 + i && *(s1 + i) != '\0'&& *(s2 + i) != '\0') 
    { 
     i++; 
    } 

    if (*(s1 + i) < *(s2 + i)) 
     answer = -1;    /* s1 < s2 */ 
    else if (*(s1 + i) == *(s2 + i)) 
      answer = 0;     /* s1 == s2 */ 
     else 
      answer = 1;     /* s1 > s2 */ 

     return answer; 

但我想將其更改爲s1++s2++ insted的的*(s1 + i)*(s2 + i)。我試圖用一個額外的指針來實現這個想法,但我失敗了。下面的代碼 - >

int compareStrings(const char *s1, const char *s2) 
{ 
    int answer; 
    char **i = s1, **j = s2; 
    // i and j - to sequence through array of characters 
    while (*(i++) == *(j++) && *(i++) != '\0'&& *(j++) != '\0'); 

    if (*i < *j) 
     answer = -1;    /* s1 < s2 */ 
    else if (*i == *j) 
     answer = 0;     /* s1 == s2 */ 
    else 
     answer = 1;     /* s1 > s2 */ 

    return answer; 
} 
+5

我認爲它更適合[代碼評論](http://codereview.stackexchange.com/) – yeputons

+1

(*(s1 + i)== *(s2 + i)&& *(s1 + i)!='\ 0'&& *(s2 + i)!='\ 0') – Yellowfun

+0

謝謝! @yeputons! – Yellowfun

回答

2

爲了比較C字符串,所有你需要的是

int str_cmp(const char* s1, const char* s2) 
{ 
    while (*s1 != 0 && *s2 != 0 && *s1 == *s2) 
    { 
     ++s1; 
     ++s2; 
    } 

    if (*s1 == *s2) 
    { 
     return 0; 
    } 

    return *s1 < *s2 ? -1 : 1; 
} 
1

後者的代碼是不工作的,因爲你增加s1兩次:

*s1++ == *s1++ 

這將:

  1. 得到s1
  2. Dereferene it
  3. 1加1
  4. 然後在右側,再次做同樣的操作
  5. 然後才能比較它。

你基本上都在做這樣的:

*(s1) == *(s1+1) 

我認爲,實際上應該是:

*s1++ == *s2++ 
+2

你確定關於'*(s1 + 1)== *(s1 + 2)'?這將是'*(s1)== *(s1 + 1)',因爲後綴增量返回舊值。 –

+0

好的。更正了! – Dan

+0

我不確定,但對於我來說,'* s1 ++ == * s1 ++'有** _未定義的行爲_ **,因爲'=='不是[sequence point](http:// stackoverflow。com/questions/3575350/sequence-point-in-c),所以,你不知道哪個's1 ++'(左邊或右邊)被首先評估。所以你絕對不能說相當於'*(s1)== *(s1 + 1)',因爲它也可以是'*(s1 + 1)== *(s1)'或別的東西(未定義的行爲) – Garf365