Why can I retrieve array which I have initialized in the same class?

I have initialized nM (an array of MagicNumber type) in the GuessMachine constructor using the setter in the MagicNumber, but when I refer to the array, it seems to be empty.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
GuessMachine::GuessMachine()
{
   
    MagicNumber nM[6];
    string prizeItem = "";
   
    for (int i = 0; i<6; i++)
    {
        cout << "Please enter an item: ";
        cin >> prizeItem;
        cin.ignore();
        nM[i].setNumber(i+1);
        nM[i].setItem(prizeItem);
       
    }
    cout << endl;

    cout << "checking 1st index is: " << nM[0].getNumber() << " " 
         << nM[0].getItem() << endl;
}

void GuessMachine::displayPrizes()
{
   
    cout <<  "checking 1st index is: " << nM[0].getNumber() << " " 
         << nM[0].getItem() << endl;
   

    return;
}


Line 25 & 26 is giving me problem. nM is an array of MagicNumber type. Why is it when I refer to nm[0] in displayPrizes(), it gives me some funny numbers, like as if it has never been initialize? But I have checked that it has been properly initialized.

Last edited on
In the constructor on line 4 you create a new array called nM. That is not the same array that you access in displayPrizes(). Removing line 4 probably solves the problem.
Topic archived. No new replies allowed.