【问题标题】:Deleting an array element declared in struct c++删除在 struct c++ 中声明的数组元素
【发布时间】:2019-01-15 16:30:09
【问题描述】:

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

#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<<"\t\t\t*********enter record**********"<<endl;
                student st[2];
                for(int count=0; count<2;count++)
                  {
                    cout<<"\t\t\t\tenter student "<<count<<" name"<<endl;
                    cin>>st[count].name;
                    cout<<"\t\t\t\tenter student "<<count<<" id"<<endl;
                    cin>>st[count].id;
                  }
                break; 

            case 5:
                cout<<"\t\t\t*********delete record********"<<endl;
                for(int count=0;count<10;count++)
                {
                    delete st[count].name;
                }    
                break;     

}

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

我想在delete的情况下删除name和id这两个元素。但是使用 delete st[count].name 会给我一个 [Warning] Deleting array 。当我运行程序时,它会给我一个程序收到信号 SIGTRAP、跟踪/断点陷阱。我是 C++ 的初学者,请帮助我如何删除存储在这些数组中的元素。谢谢

【问题讨论】:

  • 你可以delete 只能是new 动态分配的东西,这不是你的情况。
  • 那里没有可删除的内容。它是一个 char 数组,其内存分配在结构中,不能单独释放。还有为什么要使用聊天数组而不是std::string
  • 我想在案例 1 中删除我正在写入 student st[2] 的数据。我想在案例 5 中删除它
  • 你说的“删除数据”是什么意思
  • 使用memset

标签: c++ arrays dev-c++


【解决方案1】:

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

cin>>st[count].name

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

稍后,您正在使用

delete st[count].name

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

对您的程序最简单的解决方法是将char name[20] 更改为std::stringstd::string 将自行调整大小以适应其动态保存的文本,同时还负责自行清除内存,因此您不需要不用担心,以后它还有很多有用的方法,你可能会觉得有用,你可以阅读更多关于std::string的内容。

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

【讨论】:

  • 能否请您推荐我应该更改哪些代码来完成任务。我想删除我在学生 st[2] 中的案例 1 中写入的数据。
  • @UsmanAli 你能说一下“删除数据”是什么意思吗?问题是 delete 在 C++ 中具有特定含义,不适用于您的情况。你不需要/不能delete任何数据(正如这个答案正确解释的那样),但也许你想要其他可以做的事情......
  • @user463035818 我正在使用 cin>>st[count].name; 写入案例 1 中的数据;和 cin>>st[count].id;如果可能的话,我基本上想在案例 5 中删除它们。
  • @UsmanAli 如果“删除数据”是指“我希望字符串为空”,则在使用std::string 时,您可以使用std::string::clear
  • @UsmanAli “如果可能的话,我基本上想在第 5 种情况下删除它们”,“删除它们”是什么意思?如果你想在屏幕上打印一个空白字符串的名字?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 2015-07-25
  • 1970-01-01
相关资源
最近更新 更多