我正在尝试编写代码来反转字符串(我只是想在C编程和指针操作方面做得更好),但我无法弄清楚为什么我会遇到分段错误:
#include <string.h>
void reverse(char *s);
int main() {
char* s = "teststring";
reverse(s);
return 0;
}
void reverse(char *s) {
int i, j;
char temp;
for (i=0,j = (strlen(s)-1); i < j; i++, j--) {
temp = *(s+i); //line 1
*(s+i) = *(s+j); //line 2
*(s+j) = temp; //line 3
}
}
Run Code Online (Sandbox Code Playgroud)
它是第2行和第3行导致分段错误.我知道可能有更好的方法来做到这一点,但我有兴趣找出我的代码中特别导致分段错误的内容.
更新:我已根据要求包含了调用函数.