使用指向char的指针时访问冲突写入位置 [英] Access violation writing location when working with pointers to char

查看:125
本文介绍了使用指向char的指针时访问冲突写入位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个非常简单的程序,该程序将从字符串中删除重复的字符。我在Visual Studio中运行它并收到错误:

I am writing a very simple program that removes duplicate chars from a string. I ran it visual studio and got the error:


inteviews.exe中0x00d110d9的未处理异常:0xC0000005:访问冲突写入位置0x00d27830。 / p>

Unhandled exception at 0x00d110d9 in inteviews.exe: 0xC0000005: Access violation writing location 0x00d27830.

我真的不知道问题出在哪里。当前单元格获取下一个单元格的值。

I really don't see what the problem is. current cell gets the value of the next cell.

void remove(char *str, char a) {
    while (*str != '\0') {
        if (*(str+1) == a) {
            remove(str + 1, a);
        }

        *str = *(str +1 );//HERE I GET THE ERROR
        ++str;
    }
}


int _tmain(int argc, _TCHAR* argv[])
{
    char *str = "abcad";

    while (*str != '\0') {
        remove(str,*str);
        str++;
    }

    std::cout << str << std::endl;

    return 0;
}






编辑:

我已经尝试将其更改为 char str [] = abcad ,但我仍然会得到相同的错误。

I already tried to change it to char str[] = "abcad" but I still get the same error.

推荐答案

您正在尝试修改字符串文字。

You're attempting to modify a string literal. You can't do that.

char *str = "abcad";

这是一个字符串文字。它是在只读内存中创建的,因此尝试对其进行写操作会导致访问冲突。

That's a string literal. It's created in read-only memory therefore attempting to write to it is an access violation.

这篇关于使用指向char的指针时访问冲突写入位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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