計算字符串長度(不含結束符 '\0')是指針操作基礎練習。本文展示指針迭代版與遞歸版。
#include <assert.h>
int my_strlen_ptr(const char *str) {
assert(str);
int count = 0;
while (*str++) count++;
return count;
}
*str++ 先取值判斷非零,再指針後移。簡潔高效。
int my_strlen_rec(const char *str) {
if (*str == '\0') return 0;
return 1 + my_strlen_rec(str + 1);
}
遞歸關係:strlen(s) = 1 + strlen(s+1),基線 *s=='\0' → 0。
int main() {
char *s = "abcdef";
printf("指針版:%d\n", my_strlen_ptr(s));
printf("遞歸版:%d\n", my_strlen_rec(s));
system("pause");
return 0;
}
| 版本 | 時間 | 空間 | 優點 | 缺點 |
|---|---|---|---|---|
| 指針迭代 | O(n) | O(1) | 高效、無棧溢出風險 | 需理解指針運算 |
| 遞歸 | O(n) | O(n) | 邏輯清晰、教學價值高 | 長字符串棧溢出、效率低 |
assert 或返回錯誤碼if (!str) 而非 if (*str=='\0'))while (*str++) 寫成 while (str++)(判斷指針而非字符)