Hi!
I need to implement a matrix M which has the form:
double M[m][n];
, but the m and n are only known on RUN time.
I am not good in C,
I am thinking to use:
double **M;
int m, n;
int i = 0, j = 0, max = 100;
double entry[MAX];
M = ( double **) malloc(max * sizeof(double) );
if ( M == ( double **) NULL ) PRINT_ERR;
while (! EOF ) {
// read the first row and put all entries into entry[MAX],
// and decide the value n in RUN time
// n is the num of column in matrix
n = read_a_entry_in_a_row(infile, entry);
// now I have n
if ( n < max )
strcpy( &M[0][0] ,entry);
if ( n >= max )
{ max *=2 ;
M = ( double **) realloc( ( double **)M, max * sizeof(double) );
if ( M == ( double **) NULL ) PRINT_ERR;
strcpy( &M[0][0] ,entry);
}
max = 10 ;
// allocate max*n elements to M
M = ( double **) realloc( ( double **)M, max*n * sizeof(double) );
int cur_row = 1 ;
// Now read the following rows and decide the value m in RUN time
while (! EOF )
{
// read one more row and save all entries in the row
// to M[cur_row][0] - M[cur_row][n-1]
read_one_more_row(infile, &M[cur_row++])
if (cur_row > max )
{
max *= 2 ;
M = ( double **) realloc( ( double **)M, max*n * sizeof(double)
);
}
}
}
m = cur_row - 1 ;
M = ( double **) realloc( ( double **)M, m*n * sizeof(double) );
// print out all entries of Matrix
for (i = 0; i < m ; i++ )
for (j = 0; j < n ; j++ )
printf("M[%d][%d] = %f,", i, j, M[i][j]);
But I could NOT get what I want to,
something must wrong in my codes.
Would you please help?
Thanks!