0

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;
    }
5
  • 1
    Is this what you want to do? villages = new Village*[villageAmount] ? Commented Mar 15, 2019 at 0: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 Commented Mar 15, 2019 at 0:19
  • @user4581301 -- who is Crom? Never heard that one before. <g> Commented Mar 15, 2019 at 0:19
  • 2
    Recommended reading: Why should C++ programmers minimize use of 'new'? Commented Mar 15, 2019 at 0:19
  • What about std::vector<> and why do you need pointers? Can't you just use normal objects and place them in the container? Commented Mar 15, 2019 at 0:32

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

why are you using new for an array and not new[] instead? Village **villages = new Village*[villageAmount]; ... delete[] villages;
Yes mybad, I was doing some C so I was still using malloc syntax

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.