Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic allocation with DOUBLE POINTERS

I have a base class Toy and derived classes Toy_remote_car amd Toy_battery_car.

I am doing this:

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.*/

The above code(ptr=new Toy*) is creating a single pointer of type Toy(ptr[0]) which contains the object of derived class Toy_remote_car.

Now i want to write such a code:

->the number of Toy type pointers should not be predefined.

->instead i would call an add_toy function which would create a ptr that will point to the type of object i want. Furthermore if i call the add_toy function again, it should not assign the data to the previos ptr, but it should create a new ptr. The following convention may help:

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];

->furthermore i would be able to access all the previous data. In short:

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

->so it would automatically create a pointer(ptr) of type Toy whenever a new Toy is being added.

I hope i have explained well what i am trying to implement in this code.

Please please help me in this regard.

Thanks

like image 889
Rafay Avatar asked Jan 20 '23 23:01

Rafay


1 Answers

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.

like image 171
Fred Foo Avatar answered Jan 30 '23 19:01

Fred Foo