ggle
ggle

Reputation: 466

Issue with 2D Array

I am trying to map out a sudoku grid using a 2D array in C++. I have been testing the code by comparing the input to a "dump" of the 2d array. The array is 9x9. My Issue is is that the first 8 columns are all perfect. But the last column seems to be wrong in eight of the 9 cases. Why might this be?

CODE:

#include <iostream>
#include <fstream>
#include <string>

int i = 0;
int j = 0;
const char test[12] = {'e', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'};
std::string abc = "";

// Class to map out a sudoku grid
class grid {

    public:

    char board[8][8];

    void mapChars(std::string fileName) {

            int x = 0;
            int y = 0;  

            std::string line;
            std::ifstream myfile (fileName.c_str());

            if (myfile.is_open()) {
                while (getline(myfile,line)) {
                    for(std::string::size_type i = 0; i < line.size(); ++i) {
                        if(strchr(test, line[i]) != NULL){
                            if (line[i] == 'e') {
                                y++; x=0;
                            } else {
                                    board[y][x] = line[i];
                                    x++;

                            }
                        }
                    }   
                } myfile.close();
            }
    }

    void dumpMap() {
        while(j < 9){
            while(i < 9){

            std::cout << board[j][i] << ' ';
            ++i;            

            } 
            std::cout << std::endl;
            ++j;
            i = 0;
        }
    }
} sudoku;

int main() {

    sudoku.mapChars("easy1.map");
    sudoku.dumpMap();
    std::cin >> abc;
    return 0;

}

Upvotes: 1

Views: 134

Answers (1)

wolfPack88
wolfPack88

Reputation: 4203

You declare an 8 by 8 array here: char board[8][8]. If you want it to be 9 by 9, use char board[9][9]. I'm guessing you confused the declaration with indexing. When you declare char board[8][8], board has a first index that runs from 0..7 and similar second index.

The reason you get a value output instead of an error is because the output of and index out-of-bounds access is undefined. When your code tries to access board[i][j], what the executable does is use the values you gave it for i and j to determine what part of memory it is supposed to retrieve the data from. If i and j are out-of-bounds, your executable is printing out memory that is actually not associated with board at all, and are in fact garbage values, as you encountered.

Upvotes: 5

Related Questions