1

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;
    }
1201ProgramAlarm
  • 30,320
  • 7
  • 40
  • 49
  • 1
    Is this what you want to do? `villages = new Village*[villageAmount]` ? – MFisherKDX Mar 15 '19 at 00:18
  • 3
    `villages` is never assigned storage, so `villages[i]` points Crom-knows where. It needs something like `villages = new Village *[villageAmount];` But instead save youeself a LOT of pain and suffering and read up on [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) – user4581301 Mar 15 '19 at 00:19
  • @user4581301 -- who is Crom? Never heard that one before. – MFisherKDX Mar 15 '19 at 00:19
  • 2
    Recommended reading: [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – user4581301 Mar 15 '19 at 00:19
  • What about `std::vector<>` and why do you need pointers? Can't you just use normal objects and place them in the container? – Martin York Mar 15 '19 at 00:32

2 Answers2

3
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
xvnm
  • 457
  • 4
  • 14
1

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