Max Frai
Max Frai

Reputation: 64266

Array filling mistake

I can't understand what's wrong is in my program. I have such input data:

01000
11110
01000

I want to save it into: vector< vector<int> > matrix;

vector< vector<int> > fillMatrix(vector< vector<int> > matrix, int height, int width, ifstream &read)
{
    // Make 2d-array [matrix]
    matrix.resize(width);
    for (int i=0; i < width; ++i)
        matrix[i].resize(height);

    // Fill it up with data
    for (int i=0; i < height; ++i)
    {
        std::string tempLine;
        std::getline(read, tempLine);
        for (int j=0; j < tempLine.length(); ++j)
        {
            // This shows right information
            //std::cout << tempLine[j] << "  -  " << (int)(tempLine[j] - '0') << "\n";
            matrix[i][j] = (int)(tempLine[j] - '0');
        }
    }

    return matrix;
}

matrix = fillMatrix(matrix, 3, 5, ifstreamHandle);

And now, function which shows the matrix:

void showMatrix(vector< vector<int> > matrix, int width, int height)
{
    // Show the matrix
    for (int i=0; i < height; ++i)
    {
        for (int j=0; j < width; ++j)
        {
            std::cout << matrix[i][j];
        }
        std::cout << "\n";
    }
}

showMatrix(matrix, 5, 3);

And the result of showMatrix is:

01000
11100
01000

There are missed '1' in second row. What's wrong?

Upvotes: 2

Views: 96

Answers (2)

moinudin
moinudin

Reputation: 138317

When you initialise the vector, you have width and height the wrong way around. When you later read from the last two columns, the results will be undefined.

matrix.resize(width);
for (int i=0; i < width; ++i)
    matrix[i].resize(height);

should be

matrix.resize(height);
for (int i=0; i < height; ++i)
    matrix[i].resize(width);

Your fillMatrix function has width and height in a different order to that in which you call it later in showMatrix. I would advise swapping the order in fillMatrix to keep it the same as in showMatrix.

Be careful filling each row up to tempLine.length, which may be greater than width which will cause an exception. You could also just get the width and height from the vector within showMatrix instead of having these as arguments. And as @Charles says, you should really pass the vector by reference to avoid a copy being made. The vector argument in fillMatrix is currently pretty useless given that you have to return it, unless you turn it into a reference and make the function void.

Upvotes: 3

Elalfer
Elalfer

Reputation: 5338

First of all you are not consistent in your code

for (int i=0; i < width; ++i)
...
for (int i=0; i < height; ++i)

so you are creating matrix like matrix[i].resize(3) for i = 0..4, but write into it using matrix[i][j] where i = 0..2 and j=0..4

Upvotes: 3

Related Questions