[英]pointers in the function C
這段代碼工作正常。 但我想知道是否可以以更有效的方式完成?
更具體地說,這部分*(s1 + i)
如果可以通過指針(例如*s1++
*(s1 + i)
強制它逐個字符地對整個數組進行排序。 我的任務是在沒有索引數組 [] 的情況下執行此函數 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++
插入*(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;
}
為了比較 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;
}
后一個代碼不起作用,因為您將s1
增加了兩次:
*s1++ == *s1++
這會:
s1
的值你基本上是這樣做的:
*(s1) == *(s1+1)
我認為實際上應該是:
*s1++ == *s2++
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.