Possible Duplicate:
Is it possible to modify a string of char in C?
#include <stdio.h>
void reverseStr(char *str);
main()
{
reverseStr("abcdef");
}
void reverseStr(char *str) {
char *tmp = str;
char curr;
while (*tmp != '\0') {
tmp++;
}
tmp--;
while (tmp > str) {
curr = *str;
*str = *tmp;
*tmp = curr;
str++;
tmp--;
}
}
当我运行它时,我得到:
/usr/bin/runit/srun_c: line 12: 2809 Segmentation fault /tmp/run_c_executable
这到底是怎么回事?我正在为面试进行练习,我对 C 很生疏,想练习一些简单的东西,但我一辈子都搞不懂。
当我注释掉 *str = *tmp;
时,我注意到段错误消失了线,我不明白为什么这会导致段错误。
感谢帮助。
最佳答案
您无法修改常量字符串。使用字符数组代替:
char str[] = "abcdef";
reverseStr(str);
关于c - 反向 C 字符串 - 简单的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13043523/