Home > Mobile >  Multidimensional array printing wrong values in cpp
Multidimensional array printing wrong values in cpp

Time:02-10

I've been struggling with a simple class representing a matrix in C . Instead of using a multidimensional array, I've decided to use a flat array and access the values by calculating the index of the according cell by [row * x_dim col]. I want to use 2D matrices only. Ideally, I would also create getter and setter functions, but as I am already having troubles I skipped those for now. The main problem is, that after setting values, those values seem to be corrupted somewhere along the way as when printing them out again, I'm reading different values then what I've actually stored. Here's the (simplified) header MyMatrix.h:

class MyMatrix{
    public:
        int x_dim, y_dim;

        float *my_matrix;

        MyMatrix(int x, int y);
        ~MyMatrix();
};

Here is MyMatrix.cpp:

#include "MyMatrix.h"

MyMatrix::MyMatrix(int x, int y){
    x_dim = x;
    y_dim = y;

    my_matrix = new float[x * y];
}

MyMatrix::~MyMatrix(){
    delete[] my_matrix;
}

Now when creating a new instance of MyMatrix, filling the array with ascending numbers and then printing the values again, I am getting different values for some cells in the (flat) matrix. Here's what I did:

#include "MyMatrix.h"
#include <iostream>

int main(){

    MyMatrix test(3, 4);

    //filling the array in test with ascending numbers
    for(int row = 0; row < test.x_dim; row  ){
        for(int col = 0; col < test.y_dim; col  ){
            test.my_matrix[row * test.x_dim   col] = col 1;
        }
    }


    for(int row = 0; row < test.x_dim; row  ){
        std::cout << "Row " << row << ": ";
        for(int col = 0; col < test.y_dim; col  ){
            std::cout  << test.my_matrix[row * test.x_dim   col] << "  ";
        }
        std::cout << std::endl;
    }
}

So what my output should look like is this:

Row 0: 1  2  3  4  
Row 1: 1  2  3  4  
Row 2: 1  2  3  4 

But instead, it looks like this:

Row 0: 1  2  3  1  
Row 1: 1  2  3  1  
Row 2: 1  2  3  4 

As one can see, the first two rows have a 1 instead of a 4 in column 3. I've really been struggling with identifying the underlying issue here and I can't figure it out so I would appreciate any help! Thanks!

I am using clang version 13.0.0 on an M1 Pro and the g compiler.

CodePudding user response:

This is the wrong index:

 row * test.x_dim   col

Suppose you are in the last iteration of the outer loop then row == x_dim-1 and you get:

 (x_dim-1) * x_dim   col

while it should be (supposed x is rows):

 (y_dim-1) * x_dim   col

Tip: Your variable naming col vs x_dim and row vs y_dim can be made better. x, x_dim and y, y_dim or col, num_columns and row, num_rows would be less errorprone.

  • Related