在使用C (Microsoft vs)中使用指针和新运算符时出错

Error while using pointers and new operators in C++(Microsoft VS)

本文关键字:运算符 出错 指针 Microsoft vs      更新时间:2023-10-16

我正在使用指针和新操作员来打印不同的城市名称。但是Microsoft Visual Studio表明它是异常:读取访问违规。即使我编写*ptr=n;*ptr=20;,也会发生这种情况,但是如果我给出ptr=&n;(如果n是具有一定值的变量),则可以正常工作。

)。

计划显示城市名称

 #include <iostream>
#include <cstring>
using namespace std;
class city
{
protected:
    char *name;
    int len;
public:
    char *s;
    city();
    ~city();
    void getdata()
    {
        s = new char[20];
        cout << "enter the name of city" << endl;
        cin >> s;
        len = strlen(s);
        name = new char[len + 1];
        strcpy_s(name, 10, s);

    }
    void display()
    {
        cout << *name << endl;
    }
private:

};
city::city()
{
    len = 0;//initialization
    name = NULL;
}
city::~city()
{
    delete[]name;
    delete[]s;
}
int main() 
{
    city *obj[10];
    int n = 0;
    int en=0;
    do 
    {
        obj[n] = new city;
        obj[n]->getdata();
        n++;
        obj[n]->display();
        cout << "do you want to enter another city?" << endl;
        cout << "(enter 1 for yes and 0 for no"<<endl;
        cin >> en;
    } while (en);
    delete[]obj;
    system("pause");
    return 0;
}

错误的屏幕截图

不手动管理内存!使用STL忘记内存管理!

#include <iostream>
#include <string>
#include <array>
class city
{
protected:
    std::string name;
public:
    city() = default;
    //~city();
    void getdata()
    {
        std::cout << "enter the name of city" << std::endl;
        std::cin >> this->name;
    }
    void display()
    {
        std::cout << name << std::endl;
    }
};
int main() 
{
    std::array<city, 10> obj;
    for(auto&& o : obj)
    {
        o.getdata();
        o.display();
        std::cout
            << "do you want to enter another city?" << std::endl
            << "(enter 1 for yes and 0 for no" << std::endl;
        int en=0;
        std::cin >> en;
        if(0 == en) return 0;
    }
    return 0;
}

https://wandbox.org/permlink/bz4if3lndsyuizpb