在使用C (Microsoft vs)中使用指针和新运算符时出错
Error while using pointers and new operators in C++(Microsoft VS)
我正在使用指针和新操作员来打印不同的城市名称。但是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
相关文章:
- 在 myVector 类中重载运算符 + 时出错
- 使用运算符调用 void 函数时出错<set>
- 通过 [] 运算符访问unordered_map时出错
- 在重载 + 和 - 运算符时出错
- 重载运算符时出错<在 sf::Vector 中
- 将运算符<<与隐式转换的非基本数据类型一起使用时出错
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 令牌之前缺少二进制运算符 "#" 当 #define 在 #if 内时出错
- 在运算符中将联合作为参数传递时出错<<
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- 尝试重载模板类友元<<运算符时出错
- 使用 getline 重载 istream 运算符>> 会出错
- 灵气:用期望运算符替换序列时出错
- 在类外部定义显式运算符 bool() 时出错
- 擦除矢量中的对象时出错.如何将移动作业运算符添加到我的类中
- 过载运算符出错>>
- 在使用C (Microsoft vs)中使用指针和新运算符时出错
- 在C++中复制矢量时,矢量运算符出错=
- 具有std::原子成员变量的类的复制构造函数/赋值运算符出错
- JavaScript到C++的转换:%运算符出错