刚开始学C++,跟着B站的视频学发现这里
newSpace[this->m_EmpNum + i] = worker;
会出现缓冲区溢出,这是为什么?该如何解决?谢谢
[C++] 纯文本查看 复制代码 if (addNum > 0)
{
//计算新空间人数
int newSize = this->m_EmpNum + addNum;
//开辟新空间
Worker** newSpace = new Worker * [newSize];
//将原来的空间下的数据拷贝到新空间下
if (this->m_EmpArray != NULL)
{
for (int i = 0; i < this->m_EmpNum; i++)
{
newSpace[i] = this->m_EmpArray[i];
}
}
//添加新数据
for (int i = 0; i < addNum; i++)
{
int id;
string name;//姓名
int dSelect;//部门
cout << "请输入第" << i + 1 << "个新职工编号" << endl;
cin >> id;
cout << "请输入第" << i + 1 << "个新职工姓名" << endl;
cin >> name;
cout << "请选择第" << i + 1 << "个新职工部门" << endl;
cout << "1、普通职工" << endl;
cout << "2、经理" << endl;
cout << "3、老板" << endl;
cin >> dSelect;
Worker* worker = NULL;
switch (dSelect)
{
case 1:
worker = new Employee(id, name, 1);
break;
case 2:
worker = new Manager(id, name, 2);
break;
case 3:
worker = new Boss(id, name, 3);
break;
default:
break;
}
//将创建的职工指针保存到数组
newSpace[this->m_EmpNum + i] = worker;
}
|