ddacot
ddacot

Reputation: 1210

C++ Same array - different outputs

I'm trying to read from file (myfile.in) a 2D array. Rows and cols are given.

myfile>>n>>m; //rows and cols
for(int i = 0; i < n; i++) {
    for(int j =0; j < m; j++) {
    myfile>>tab[i][j];
    cout<<tab[i][j]<<" ";
    }
    cout<<endl;
}

and the output on the screen is as it should be (as it is in file):

1 0 0 0 1 0 1
0 1 1 1 1 0 0
0 0 1 0 1 1 0
0 1 0 0 1 0 0
0 1 0 0 0 1 1
1 1 1 1 0 0 0
0 1 0 0 0 1 1

after that i tryied to print the array separately.

for(int i = 0; i < n; i++) {
    for(int j =0; j < m; j++) {
    cout<<tab[i][j]<<" ";
    }
    cout<<endl;
}

and the output is:

0 1 0 0 0 1 1
0 1 0 0 0 1 1
0 1 0 0 0 1 1
0 1 0 0 0 1 1
0 1 0 0 0 1 1
0 1 0 0 0 1 1
0 1 0 0 0 1 1

actually it's showing the last row, why?

Upvotes: 1

Views: 77

Answers (2)

Andrei B&#226;rsan
Andrei B&#226;rsan

Reputation: 3523

According to your comment, you are actually initializing tab to be tab[0][0]. I don't know how come the compiler allows that, but the important thing is that you're writing outside your array bounds, triggering undefined behavior.

Try dynamically allocating your array after reading in n and m:

int n, m;
file >> n >> m;

int **tab = new int* [n];
for(size_t i = 0; i < n; ++i)
{
  tab[i] = new int[m];
}

This way you'll always be sure to allocate only as much memory as you need.

Also, don't forget to delete the array when you're done:

for(size_t i = 0; i < n; ++i) delete[] tab[i];
delete[] tab;

As you can see this method tends to add a bit too much unnecessary complexity. An elegant alternative would be using a container such as a std::vector<std::vector<int>>:

using namespace std;

vector<vector<int>> tab;

  for(int i = 0; i < n; ++i) {
    vector<int> current_row;
    for(int j = 0; j < m; ++j) {
      int buff;
      file >> buff;
      current_row.push_back(buff);
    }

    tab.push_back(current_row);
  }

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

int n=0, m=0; int tab[n][m];

This is not legal C++ for two reasons:

  1. Dimensions of an array must be constant expressions. n and m are not.

  2. You are creating an array of 0 size.

    If the constant-expression (5.19) is present, [...] its value shall be greater than zero.

Your compiler is accepting it because it has extensions that accept both of these. Nonetheless, your array has size 0 and so it has no elements. Anything you attempt to write to it will be outside the bounds of the array.

Reading myfile>>n>>m; doesn't automatically change the size of the array. You already declared it as being size 0. Nothing you do will change that.

Instead, you'd be much better off using a standard library container, such as a std::vector, which can change size at run-time. Consider:

myfile >> n >> m;
std::vector<std::vector<int>> tab(n, std::vector<int>(m));

You can then use this tab object in exactly the same way as you have above.

Upvotes: 1

Related Questions