删除在结构 c++ 中声明的数组元素



我想删除在学生结构下声明的数组元素。我只包含部分代码以减少混淆。请在下面找到两个相关案例的代码:

#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
struct student
{
char name[20];
int id;
};
struct teacher
{
char name[20];
int id;
};
int main()
{
            case 1:
                cout<<"ttt*********enter record**********"<<endl;
                student st[2];
                for(int count=0; count<2;count++)
                  {
                    cout<<"ttttenter student "<<count<<" name"<<endl;
                    cin>>st[count].name;
                    cout<<"ttttenter student "<<count<<" id"<<endl;
                    cin>>st[count].id;
                  }
                break; 
            case 5:
                cout<<"ttt*********delete record********"<<endl;
                for(int count=0;count<10;count++)
                {
                    delete st[count].name;
                }    
                break;     
}

如案例 5 所示,我尝试使用删除 st[count].name 删除数组中的元素;

我想删除删除案例中的名称和 id 元素。但是使用删除 st[count].name 给了我一个 [警告] 删除数组 .当我运行该程序时,它给了我一个程序接收信号SIGTRAP,跟踪/断点陷阱。我是 c++ 的初学者,请帮助我如何删除存储在这些数组中的元素。谢谢

您的代码中有 2 个主要问题。

cin>>st[count].name

您正在用用户输入填充数组,但数组只能容纳 20 个元素(最后一个必须是 null 终止符(,如果用户输入的文本包含超过 19 个元素,您的程序将导致未定义的行为。

稍后,您将使用

delete st[count].name

您在堆栈上分配的数组上使用delete,这又是未定义的行为,如果您使用运算符 new 重新定位对象,则只需要使用 delete ,您还应该使用 delete[] 而不是数组的delete

对程序最简单的解决方法是将char name[20]更改为 std::stringstd::string会调整自身大小以适应它动态持有的文本,同时还会在自己之后处理 clearning 内存,所以你不必担心,稍后它还有许多有用的方法,你可能会发现很有用, 您可以阅读有关std::string的更多信息。

https://en.cppreference.com/w/cpp/string/basic_string

最新更新