使用双指针进行动态分配

时间:2011-04-19 19:40:05

标签: c++ pointers memory-leaks memory-management new-operator

我有一个基类玩具和派生类Toy_remote_car和Toy_battery_car。

我这样做:

Toy** ptr;
ptr=new Toy*;
ptr[0]=new Toy_remote_car[1];
ptr[1]=new Toy_battery_car[1];/*this is completely wrong according to my teacher because i never created ptr[1]. Instead this is a misuse of memory according to him.*/

上面的代码(ptr = new Toy *)正在创建一个类型为Toy(ptr [0])的指针,它包含派生类Toy_remote_car的对象。

现在我想写这样的代码:

- >不应预定义玩具类型指针的数量。

- >相反,我会调用add_toy函数,它会创建一个指向我想要的对象类型的ptr。此外,如果我再次调用add_toy函数,它不应该将数据分配给previos ptr,但它应该创建一个新的ptr。以下惯例可能有所帮助:

ptr[0]=new Toy_remote_car[1];
/*we want to add more toys so add_toy function called. A check is applied.*/
/*The check checks that ptr[0] already contains a value so it creates another pointer ptr[1]*/
ptr[1]=new Toy_battery_car[1];

- >此外,我将能够访问所有以前的数据。简而言之:

ptr[0]//contains one type of data.
ptr[1]//contains another type.
//and so on

- >所以只要添加新玩具,它就会自动创建一个Toy类型的指针(ptr)。

我希望我已经在本代码中解释了我想要实现的内容。

请在这方面帮助我。

由于

2 个答案:

答案 0 :(得分:7)

Toy **ptr = new Toy *[n];

其中n包含您想要的Toy指针数。增长阵列很难,但可以做到:

// 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;
}

请注意,如果分配失败,则不会清除旧的toypp及其中的所有指针。实际上,如果您想要一个增长的数组,请使用vector<Toy*>代替:

vector<Toy*> toy_ptrs(n);

并使用push_back添加玩具。

不要忘记delete每一个Toy*,并使用第一种方法delete[] Toy**

可以通过继承来处理各种数据。

答案 1 :(得分:0)

我用非常简单的逻辑提出了这段代码。这完全正常。请看一看并给出意见。

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;

}
相关问题