一種是內存錯誤吧,例如訪問了未定義的某塊內存空間,int arr[8];但是訪問了arr[8]這個元素。或者int *n = NULL; *n = 10;這種也會報內存錯吧。還有就是有endless loop吧,可能沒有能使程序跳出某循環的條件存在。
方法一:
程序:
char* reverseString(char* s) {
int i,n;
n = strlen(s);
char *r = (char*)malloc(sizeof(char)*(n+1));//注意內存個數n+1
for (i = 0; i < n; i++)
{
*(r + n - 1 - i) = *(s + i);
}
r[n] = '\0';//注意而且必須放在循環外面!!!
return r;
}
方法二;
C/C++ strlen(str)和str.length()和str.size()都可以求字符串長度,其中str.length()和str.size()是用於求string類對象的成員函數,strlen(str)是用於求字符數組的長度,其參數是char*
char* reverseString(char* s) {
int i=0,n;
n = strlen(s)-1;
while (i<n)
swap(s[i++], s[n--]);
return s;
}
而在c++中:
class Solution {
public:
string reverseString(string s) {
int i = 0, j = s.size() - 1;//或者s.length
while(i < j){
swap(s[i++], s[j--]);
}
return s;
}
};