语境
我正在学习 C,我正在尝试使用指针来反转字符串。(我知道您可以使用数组;这更多是关于学习指针。)
问题
尝试运行下面的代码时,我不断收到分段错误。GCC似乎不喜欢这*end = *begin;
条线。这是为什么?
特别是因为我的代码几乎与已经在另一个问题中讨论过的非邪恶 C 函数相同
#include <stdio.h>
#include <string.h>
void my_strrev(char* begin){
char temp;
char* end;
end = begin + strlen(begin) - 1;
while(end>begin){
temp = *end;
*end = *begin;
*begin = temp;
end--;
begin++;
}
}
main(){
char *string = "foobar";
my_strrev(string);
printf("%s", string);
}