Dynamic allocation with DOUBLE POINTERS

我与影子孤独终老i 提交于 2019-12-04 10:31:30
Toy **ptr = new Toy *[n];

where n holds the number of Toy pointers you want. Growing the array is hard, but it can be done:

// Add x to toypp, an array of n pointers
// very stupid, linear-time algorithm
Toy **add_toy(Toy *x, Toy **toypp, size_t n)
{
    Toy **new_toypp = new Toy*[n+1];

    // copy the old array's contents
    for (size_t i=0; i<n; i++)
         new_toypp[i] = toypp[i];
    toypp[n] = x;

    // clean up
    delete[] toypp;

    return new_toypp;
}

Note the if the allocation fails, the old toypp and all pointers in it are not cleaned up. Really, if you want an array that grows, use a vector<Toy*> instead:

vector<Toy*> toy_ptrs(n);

and add toys with push_back.

Don't forget to delete every single Toy*, and with the first method, to delete[] the Toy**.

Handling various kinds of data can be done with inheritance.

Rafay

I have come up with this code with a very simple logic. And this is working completely fine. Please give a look and do give opinions.

void add_toy_var()
{   
    temp=NULL;
    temp=tptr;
    tptr=NULL;
    delete[] tptr;
    C1.count1++;
    tptr=new Toy*[C1.count1];
    if(temp!=NULL)
    {
        for(int i=0; i<(C1.count1-1); i++)
        {
            tptr[i]=temp[i];
        }
    }


    int choice2;
    cout<<"Which Toy you want to add?"<<endl;
    cout<<"1. Remote Toy Car"<<endl;
    cout<<"2. Batt powered toy car"<<endl;
    cout<<"3. Batt powered toy bike"<<endl;
    cout<<"4. Remote control toy heli"<<endl;
    cin>>choice2;
    if(choice2==1)
    {                       
        tptr[C1.count1-1]=new Toy_car_rem[1];
        tptr[C1.count1-1]->set_data();
    }
    else if(choice2==2)
    {
        tptr[C1.count1-1]=new Toy_car_batt[1];
        tptr[C1.count1-1]->set_data();
    }
    else if(choice2==3)
    {
        tptr[C1.count1-1]=new Toy_bike_batt[1];
        tptr[C1.count1-1]->set_data();
    }
    temp=NULL;
    delete[] temp;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!