-3

I have a table availableRows which contains integers values. When I display the value of availableRows[0] for the first time, it shows the correct value. But then, in the for loop, it shows a completely different number which is 512.

What did I do wrong ?

    int row;
    int randomColumn;
    int *availableRows = getAvailableRows(); 
    cout << availableRows[0]; // It shows the correct value

for (int column = 0; column < COLUMN_GRID; column++){
    row = availableRows[column];
    cout << row; // But here it shows 512, why ?
    /* Simulates a winning point */
    if (row != -1 && simulateWin(row, column)){
        GRID[row][column] = COMPUTER;
        COUNT += 1;
        return;

    }
}



int *getAvailableRows(){
    int availableRows[7] = {-1, -1, -1, -1, -1, -1, -1};

for (int column = 0; column < COLUMN_GRID; column++){
    for (int row = 0; row < ROW_GRID; row++){
        if (GRID[row][column] == NONE){
            availableRows[column] = row;
            break;
        }
    }
}
return availableRows;

}

EDIT : I added the getAvailableRows() function.

Could somebody explain me why what I've done is bad ? I don't really understand pointers very well.

tonystrawberry
  • 102
  • 1
  • 2
  • 12
  • 2
    You need to show getAvailableRows - my bet: you're returning a pointer to a local variable... – Mat Jun 10 '14 at 17:59
  • Show a minimal code sample that reproduces the problem or it didn't happen. – juanchopanza Jun 10 '14 at 17:59
  • http://stackoverflow.com/questions/8708803/returning-pointer-to-local-function-variable <- start here, follow all the duplicates and related links – Mat Jun 10 '14 at 18:08

1 Answers1

1

I can guess that function getAvailableRows returns pointer to a local array (more precisely to the first element of a local array) defined in the function. So the behaviour of the program is undefined because the life of the array will be ended after exiting the function (it can be overwritten by other data).

EDIT: As you showed the code of the function that confirmed my guess then change the function the following way

std::array<int, 7> getAvailableRows(){
    std::array<int, 7> availableRows = {-1, -1, -1, -1, -1, -1, -1};

for (int column = 0; column < COLUMN_GRID; column++){
    for (int row = 0; row < ROW_GRID; row++){
        if (GRID[row][column] == NONE){
            availableRows[column] = row;
            break;
        }
    }
}
return availableRows;

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335