題目 - leetcode
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
C 解題
char* reverseString(char* s) {
int i = 0;
while (s[i] != '\0') {
i++;
}
int length = i;
char *temp = (char *) malloc ((length + 1) * sizeof(char));
for (int j = length; j >= 0; j--) {
temp[length-j] = s[j-1];
}
return temp;
}
糾錯
首先是在計算字符串長度的時候,結尾嘗試了 “EOF”,但是這樣初始化的字符串,其結尾應該是“\0”,導致結尾判斷失敗。
其次是在反向復制的時候,把結尾的“\0”復制到了第一個,導致復制的字符串直接就結束了。