Avraham Batoniashvili
Avraham Batoniashvili

Reputation: 19

Dynamic object creation of an array of pointers

I try to create objects dynamically. Each object is a pointer in an array of pointers. The compiler gives me

error C4700: uninitialized local variable 'villages' used.

And I can not figure out how to fix it. I would be very grateful to all the helpers.

    int villageAmount;
    cout << "Defining villages:\n\nEnter how many villages do you want: ";
    cin >> villageAmount;
    Village **villages;
    for (int i = 0; i < villageAmount; i++)
    {
        cout << "\nDefining village's details #" << i + 1 << ":\n";
        villages[i] = new (nothrow) Village;
    }

Upvotes: 0

Views: 88

Answers (2)

Guillaume Magniadas
Guillaume Magniadas

Reputation: 176

villages memory is never allocated, you should use a vector or any sort of container (an array look fine here). If you really want to allow the memory manually you could do something like :

Village **villages = new Village*[villageAmount];

Don't forget to free EVERY new, (If you only free villages, all the Village* that he contain will remain allocated.

Edit : someone else answered so I guess my answere is usless

Upvotes: 1

xvnm
xvnm

Reputation: 481

Village **villages;

you declared villages without initializing, so it contains garabage valaue.

for (int i = 0; i < villageAmount; i++)
{
    cout << "\nDefining village's details #" << i + 1 << ":\n";
    villages[i] = new (nothrow) Village;
}

right below, you access into it and writes. That's no no.

If you want to store pointer of village (i.e. type of Village*) dynamically, you also need to allocate them.

Village **villages = new Village*[villageAmount];

Or if amount is fixed,

Village *villages[10] = { nullptr, }; // 10, 12344, or whatever

Upvotes: 3

Related Questions