這段代碼工作正常。但我想知道是否可以以更有效的方式完成?函數指針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;
}
我認爲它更適合[代碼評論](http://codereview.stackexchange.com/) – yeputons
(*(s1 + i)== *(s2 + i)&& *(s1 + i)!='\ 0'&& *(s2 + i)!='\ 0') – Yellowfun
謝謝! @yeputons! – Yellowfun