2D Array storing wrong values?

Hi, I am storing 4x4 temperature data in a 2D array, however when I try to call the array to print values after storing the data, the values at row 0,1,2 of column 3 are incorrect.

I created a C++ MRE below of the issue:

#include <iostream>

using namespace std;

int frameBuff[35] = { 16,1,248,0,8,1,40,1,254,0,247,0,9,1,68,1,23,1,254,0,52,1,76,1,72,1,30,1,10,1,70,1,69,1,216 };

double tempArr[3][3];

int main()
{
    int y =0;
    int x =0;
    int i =0;
    double val =0;
    //store in array
    for (int y=0; y<4; y++){
        cout<<"\n";
        for (int x=0; x<4; x++){
            i = x + (y * 4);
            val = frameBuff[(i * 2 + 2)] + (frameBuff[(i * 2 + 3)] << 8);
            tempArr[y][ ] = val * 0.1;
            cout<<tempArr[y][x];
            cout<<" | ";
        }
    }
    
    //confirm values - the output of this for loop has the issue
    cout<<"\n";
    for (int y=0; y<4; y++){
        cout<<"\n";
        for (int x=0; x<4; x++){
            cout<<tempArr[y][x];
            cout<<" | ";
        }
    }

    return 0;
}

With [3][3] you are not creating a 4x4 but a 3x3 array - the number in square brackets stands for the number of elements not the maximum index of elements (that would be a very confusing way of allocating an array).

Hi,
code which you provided can’t be compiled because
this:

 tempArr[y][ ] = val * 0.1; 

but when I change this to:

 tempArr[y][x] = val * 0.1;

and then changed

double tempArr[3][3];

to

double tempArr[4][4];

all works fine

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.