访问冲突错误时反转字符串c ++ [英] Access violation error when reversing a string c++

查看:146
本文介绍了访问冲突错误时反转字符串c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么在写入字符串时会出现分段错误?

以下简单函数应该将字符数组反转。

The following simple function should reverse a character array in place.

void reverse(char* str)
{
    char* last = str;

    // find end of the string
    while(*last) {
        ++last;
    }

    // swap characters until the pointers meet in the middle
    while(str < last)
    {
        --last; 
        char temp = *str;
        *str = *last;
        *last = temp;
        ++str;
    }
}

int main()
{
    char* a= "Hello";
    reverse(a);
    return 0;
}

代码编译。但它抛出一个关于访问冲突的运行时错误。根据调试器,罪魁祸首是下面的行:

The code compiles. But it throws a runtime error about access violation. According to the debugger the culprit is the line below:

char temp = *str;

任何想法为什么会发生?

Any ideas why it happens?

推荐答案

char* a= "Hello";

指针 a 指向字符串。根据标准,尝试修改字符串字面值导致未定义的行为。在你的实现的情况下,分段错误表明编译器选择将字符串字面量放在不可修改的内存中。

The pointer a points to a string literal. According to the standard, attempting to modify a string literal results in undefined behaviour. In the case of your implementation, the segmentation fault indicates that the compiler is choosing to place the string literal in non-modifiable memory.

声明 为可修改的字符串。例如,像这样:

Declare a to be a string that is modifiable. For example, like this:

char a[] = "Hello";

这篇关于访问冲突错误时反转字符串c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆