0

How come when i assign for a point in the matrix it assigns the value for the whole column? I am trying to get it to assign only at that point. Currently I am teaching myself the 2nd part of my computer science class so I am playing with this. My file just assigns the size of the matrix. IT compiles and no run time errors. I am using codeblocks. Any better IDEs?

my sample.txt file grabs two numbers for now 3 and 5. I am trying to understand so I can implement the rest of the file to put values in the correct points in the matrix.

#include <iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;

int main()
{
   // variable initialition
   string fileName;
   int value;
   int row=0,col=0; //for size of array
   int a[row][col];
   int row2,col2; // for putting values in array

   fileName="sample.txt";
   ifstream input;
   input.open("sample.txt");

   if (!input)
   {
      cout<<"ERROR: BAD FILE";
   }


   input>>row;
   input>>col;
   cout<<" ROW :"<<row<<endl;
   cout<< " COL :"<<col<<endl;


   for (int indexRow=0; indexRow<row; indexRow++)
   {


      for (int indexCol=0; indexCol<col; indexCol++)
      {
         a[indexRow][indexCol]=0;
      }
   }


   a[0][1]=232;

   for (int row2=0; row2<row; row2++)
   {
      for (int col2=0; col2<col; col2++)
      {


         cout<<a[row2][col2]<<" ";
      }

      cout<<endl;
   }




   input.close();

   return 0;
}
Cferrel
  • 321
  • 2
  • 5
  • 19
  • Don't tell me this compiles... I mean, you have a run-time error or, as I expect, compile-time error? – lapk Dec 17 '11 at 02:46
  • 1
    Ok, you edited post and saying it compiles (and runs)... I don't understand how `int row = 0, col = 0; int a[ row ][ col ];` compiles. It's TWICE against the Standard: it's variable-size array AND zero-size array at the same time! – lapk Dec 17 '11 at 02:53
  • @AzzA: g++ is happy to let you use arrays with variable size like that unless you use the `-ansi` and/or `-pedantic` flags. I think that allowing that by default is a terrible idea on their part. – Chris Parton Dec 17 '11 at 04:35

1 Answers1

2

Dynamic arrays are not as simple as that in C++. The syntax you used is for creating fixed-size arrays only. In such case, you need to create your 2D arrays with constant, non-zero values, like the following:

int a[10][10];

Also,

input>>row;
input>>col;

... will definitely not resize your array automatically.

You should avoid using raw arrays anyway, and consider using a vector of vectors for your 2D array:

std::vector<std::vector<int>> a;

Please have a look at the following question for more alternatives and discussions about dynamic arrays:

How do I best handle dynamic multi-dimensional arrays in C/C++

Community
  • 1
  • 1
Jem
  • 2,255
  • 18
  • 25