簡體   English   中英

在C ++(Microsoft VS)中使用指針和新運算符時出錯

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

我正在使用指針和新運算符來打印不同的城市名稱。 但是Microsoft Visual Studio顯示它拋出了Exception:read access exception 即使我寫*ptr=n;也會發生這種情況*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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM