简体   繁体   English

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

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

i was using pointers and new operator for printing different city names. 我正在使用指针和新运算符来打印不同的城市名称。 But the Microsoft Visual Studio show that it is Exception thrown:read access violation . 但是Microsoft Visual Studio显示它抛出了Exception:read access exception This happen even when i write *ptr=n; 即使我写*ptr=n;也会发生这种情况*ptr=n; or *ptr=20; *ptr=20; ,but works properly if i give ptr=&n; ,但是如果我给ptr=&n;可以正常工作 (if n is the variable with some value). (如果n是具有某个值的变量)。

Program to display names of cities 程序显示城市名称

 #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;
}

Screenshot of error 错误的屏幕截图

Don't manage memory manually! 不要手动管理内存! Use STL to forget memory manage! 使用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 https://wandbox.org/permlink/bz4iF3LNDSyUIZPb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM