Can't assign in an array of pointers

103 views Asked by At

My problem is in adaugare function on this line I think persoane[numar_persoane] = pers. Because that line gives me this error. What problem do I have?

I have to use a dynamic array of pointers.

class baze
    {
    private: int numar_persoane=0;
             persoana (*persoane)=(persoana *)malloc(0);

public:  baze()
     {

             persoane = NULL;

     }
     ~baze()
     {
         delete[] persoane; //???????????
     }

     void adaugare(persoana pers)
     {

         numar_persoane++;
            realloc(persoane, sizeof(persoana)*numar_persoane);
         persoane[numar_persoane] = pers;

     };
 void afisarealfa()
         {
             for (int i = 0; i < numar_persoane; i++)
             for (int j = i + 1; j < numar_persoane; j++)
             if (persoane[i].gnume()>persoane[i].gnume())
             {
                 persoana aux;
                 aux = persoane[i];
                 persoane[i] = persoane[j];
                 persoane[j] = aux;
             }
             for (int i = 0; i < numar_persoane; i++)
             {
                 cout << "Nume:" << persoane[i].gnume() << endl;
                 cout << "Varsta" << persoane[i].gan() << endl;
                 cout << "sex" << persoane[i].gsex();
             }
}

This is persoana class:

class persoana
{
private: string nume;
         int an;
         char sex;
public: void snume(string numebagat)
{
            nume = numebagat;
}
        string gnume()
        {
            return nume;
        }
        void san(int anbagat)
        {
            an = anbagat;
        }
        int gan()
        {
            return an;
        }
        void ssex(char sexbagat)
        {
            sex = sexbagat;
        }
        char gsex()
        {
            return sex;
        }

};

Main:

int _tmain(int argc, _TCHAR* argv[])
{
    persoana a;
    a.san(1990);
    a.snume("Gogu");
    a.ssex('m');
    cout << "Nume: " << a.gnume() << endl << "Anul nasterii: " << a.gan() << endl << "Sex: " << a.gsex();
    baze b;
    b.adaugare(a);
    return 0;

}
1

There are 1 answers

0
Foon On
  1. As @simpletron pointed out, malloc(0) is kind of weird. I wasn't even sure it was legal, but per what's the point in malloc(0)?, it is legal albeit implementation defined (it might be NULL, it might be a valid empty region; either way, you can call free on it, and per Is a malloc() needed before a realloc()? you can just skip that malloc;
  2. Using malloc but then delete is not recommended; per Behaviour of malloc with delete in C++, this IS undefined behavior; you should probably be using free to go with realloc instead of delete
  3. You have an off by one error. You should use persoane[numar_persoane-1] = pers;
  4. You probably should set age/sex to some default value in the constructor.
  5. This might be my personal preference, but I dislike copying classes around versus pointer to classes.