正在删除* char [] [英] Deleting *char[]

查看:100
本文介绍了正在删除* char []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试删除一个字符,我得到访问冲突错误。

If I try to delete a char I get an access violation error.

我的代码:

int main()
{
    char *myString = new char[32];
    myString = "Hello";
    cout << myString;
    cin.get();

    delete [] myString;
    return 0;
}

Ive也尝试了

delete myString

/ p>

but im still get access violation errors

推荐答案

行后

 myString = "Hello";

指针 myString 不再指向数组,但是一个字符串字面量。

the pointer myString no longer points to the array you've allocated, but to a string literal. The line

delete [] myString;

然后尝试删除文字(导致崩溃)。

then attempts to delete the literal (which results in a crash).

可以使用 strcpy 复制一个字符串,或者使用 std :: string

You can copy a string with strcpy, or better yet, use std::string.

std::string myString = "Hello";
cout << myString;

这篇关于正在删除* char []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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