c++ - 使用我的 strupr 实现时程序崩溃

标签 c++ pointers toupper

我已经从字符串库中编写了 strupr 函数的实现。当我调用这个函数时,程序崩溃了。我已经找到了另一种让它工作的方法,但我想知道为什么这个版本不起作用。程序恰好在执行 *str = (*str) - 32; 指令时崩溃。

#include <iostream>

using namespace std;

char * my_strupr(char * str)
{
    char * result = str;

    while(*str != '\0')
    {
        if(*str >= 'a' && *str <= 'z') *str = (*str) - 32;
        str ++;
    }

    return result;
}

int main()
{
    char * str = "some text";
    cout << my_strupr(str);
    return 0;
}

在这种情况下我必须使用指针,它们在我的任务中是必需的。

最佳答案

编译器将字符串存储在只读内存中,而您在尝试修改此内存时遇到段错误。 这是讨论 here

关于c++ - 使用我的 strupr 实现时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46731182/

相关文章:

c++ - 对数组中的整数进行排序。但它不适用于某些情况

c++ - 如何使用 GCC 4.4.6 从 RHEL6 机器编译 RHEL5 兼容共享库?

c - 为什么不能将 `char **` 传递给在 C 中采用 `const char **` 的函数?

c# - 如何在 C# 中声明 C++ 指针

coding-style - 比较大写或小写是否更常见/标准?

c++ - 定义不确定大小的数组

c++ - 为什么找不到 DirectX 模板?

c++ - 为什么不能同时定义两个指针?

c++ - 为什么这些礼帽在这样使用时会有所不同?

C : Process keeps exiting before being able to input anything