Link to home
Start Free TrialLog in
Avatar of anarki5
anarki5

asked on

Problem with Matrix

Hello Friends,

I have a text file with the following contents
3
1 3 46
1 2 67
2 3 12

the first line tells me that i have a 3 x 3 matrix
now my matrix should look like this
  1  2  3
1 0 67 46
2 -  0 12
3 -  -  0

this is my code
#include <iostream.h>

#include <fstream.h>

int main()
{
     int a,b,c,d,m,i,j;
     ifstream inClientFile("clients.txt");

     if(!inClientFile)
     {
          cerr << "File could not be found:\n";
     }
     inClientFile >> a ;
     cout << a<<"\n";
         int *m = new int[a][a];

     inClientFile.ignore(1024,'\n');

     for (i=0;i<=a;i++)
          for (j=0;j<=a;j++)
          {
               if (i=j)
               {
                    inClientFile >> b >> c >> d;
                    cout << b <<" "<< c <<" "<<d<<"i=j"<<"\n";
                    //m[i][j] = 0;<-- says error C2109: subscript requires array or pointer type .
               //     i = b;
               //     j = c;
               //     m[i][j] = d;
               }
               else
                        exit();
     //cout << m[i][j];
          }
     return 0;
}

How can i insert the third value accordingly.
Please help me create my Matrix array dynamically.
Thank you.
Avatar of efn
efn

You can't create a two-dimensional array with the new operator, and you can't put two subscripts on an integer pointer, because the compiler doesn't know how big your rows are.

This FAQ answer will tell you how to create and use a dynamically allocated two-dimensional array:

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.15
ASKER CERTIFIED SOLUTION
Avatar of akshayxx
akshayxx
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mayank S
>> You can't create a two-dimensional array with the new operator

Why not? Its done exactly the way Akshay has done. First, allocate memory for an array of pointers, then allocate memory in a loop and assign the base addresses to those pointers.

Mayank.
Perhaps I was a bit too terse.  I meant you can't do it the way anarki5 tried to do it:

int *m = new int[a][a];

Certainly it's possible to allocate some memory with the new operator and use the memory as a two-dimensional array.  The FAQ I cited describes the approach Akshay used and others.
Avatar of anarki5

ASKER

Thank you very much akshayxx.
Mayank and efn Thank you for the support guys. All's fair in the game when you want to learn.