PDA

View Full Version : Matrix in Dynamic.....help


toezaurus81
06-12-04, 09:54 PM
I want to code dynamic in array, asking user input how many row and col they want the matrix to be, but input=new int[row][col]; with error, how come?


#include<iostream.h>
#include<stdlib.h>

void main ()
{ int row, col;
int *input;
input=new int[row][col];

cout<<"How many numbers of row(s) do you wish to type in? ";
cin>>row;
cout<<"How many numbers of column(s) do you wish to type in? ";
cin>>col;

if (input == NULL)
exit (1);

for (int r=0; r<row; r++)
{
for (int c=0; c<col; c++)
{
cout<<"Enter the value for row "<<r+1<<" column "<<c+1<<" : ";
cin>>input[r][c];
}

}
/*
cout << "You have entered: ";

for (n=0; n<i; n++)
cout << l[n] << ", ";
*/
delete[] input;

}

Zetr0
06-13-04, 07:05 AM
I want to code dynamic in array, asking user input how many row and col they want the matrix to be, but input=new int[row][col]; with error, how come?



heys there,

allocation of a multi-dimensional array using the NEW operator is the stuff nightmares are made of.. besides i am not too sure it can be done that way ie in one instance.. i know you can allocate many instances of an item but i am sure not multiple instances of instances LOL... i had a simular problem a while back let me offer you this different method..

// ALLOCATE A TWO-DIMENSIONAL SPACE, INITIALIZE, AND DELETE IT.

#include <exception>
#include <iostream>

using std::cout;
using std::endl;
using std::cin;

void display(long double **);
void de_allocate(long double **);

int m = 3; // THE NUMBER OF ROWS.
int n = 5; // THE NUMBER OF COLUMNS.

int main(void)
{
int **data;

// capture rows and colums from user

cout<<"How Many Rows?"
cin>>m;
cout<<"how many colums?"
cin>>n;

//obviously you have error checked and converted the ascii vals to integer
//values :)


try
{ // TEST FOR EXCEPTIONS.
data = new long double*[m]; // STEP 1: SET UP THE ROWS.
for (int j = 0; j < m; j++)

data[j] = new long double[n]; // STEP 2: SET UP THE COLUMNS
}
catch (std::bad_alloc)
{ // ENTER THIS BLOCK ONLY IF bad_alloc IS THROWN.
// YOU COULD REQUEST OTHER ACTIONS BEFORE TERMINATING
cout << "Could not allocate. Bye ...";
exit(-1);
}

for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
data[i][j] = i + j; // ARBITRARY INITIALIZATION

display(data);
de_allocate(data);
return 0;

}

void display(int **data)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cout << data[i][j] << " ";
cout << "\n" << endl;
}
}


void de_allocate(int **data)
{
for (int i = 0; i < m; i++)
delete[] data[i]; // STEP 1: DELETE THE COLUMNS

delete[] data; // STEP 2: DELETE THE ROWS

}


this lot has been pretty much lifted from borland help files ( slightly modified ) you dont need to use the try or catch methods ( if )s work just fine thusly you dont need <exception.h>

well i hope this helps..

good luck..