Search code examples
c++arraysdynamicallocation

Using dynamic allocation to create an array and insert elements into it


I want to make a library management system as an assignment

class student
{
          char ID_number[30];
          char Student_name[30];
      public:
          void create_student()
          {
                    cout<<"\nEnter The ID Number ";
                    cin>>ID_number;
                    cout<<"\n\nEnter The Name of The Student: ";
                    cin>>Student_name;

                    cout<<"\n\nStudent Created Successfully"<<endl;
          }
          void show_student()
          {
                    cout<<"\nID Number: "<<ID_number;
                    cout<<"\nStudent Name: ";
                    cin.getline(Student_name,30);


          }

How would i go about using dynamic allocation to make every new entry go into an array and use pointers to show a certain student?

I am really bad at this particular part, thanks in advance!


Solution

  • If by dynamic you mean you want to create "a few" stduent records, but aren't sure how many you don't need to worry about new or delete. Just use a vector.

    std::vector<student> students;
    while(!bored)
    {
        student latest;
        latest.creat_student(); // this looks a bit odd, perhaps it should be a free function...
        vector.push_back(latest);
        //TODO - see if I am bored yet
    }
    

    Now we have students. You said you wanted to use pointers to display them. Or rather a certain student. You haven't described how you will choose a "certain student", so let's show them all first

    for (auto item : students)
    {
        item.show_student();
    }
    

    Disappointingly, your show_student method isn't declared const, which you should consider.

    To index to a particular student, you could use students[17]. Or which ever index you want. You might be able to use std algorithms to find students with particular properies, if you provide a way to get the properties (and of course consider using std::string instead of char *)


    If you really want to use a raw array of student, then something like this works, but you will get into reallocs etc if 5 or whatever you choose isn't enough. Which is a compelling reason for choosing a std::vector.

    student * them = new student[5];
    for (size_t i = 0; i < 5; ++i)
    {
        student latest;
        latest.create_student();
        them[i] = latest;
    }
    
    for (size_t i = 0; i < 5; ++i)
    {
        them[i].show_student();
    }
    delete[] them;