c - 反向 C 字符串 - 简单的错误

标签 c string pointers segmentation-fault

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/

相关文章:

c - 如何在 C 中逐行读取 .txt?

c - Makefile 默认行为

c - 用单个字符声明整个字符串

具有不同参数的函数的 C 冲突类型

java - 从 Android 手机发送字符串到 PC

java - 小数格式与字符串格式

c - 词法分析器: how to identify the end of a token

swift - 重叠访问指针

c - 如何传递指针并在堆上分配空间

C 将字符串文字与返回字符指针的函数进行比较