Ciao a tutti,
sto scrivendo una funzione per riempire una matrice in maniera più o meno agevole! Essa funzione benissimo nel caso di debba riempire una funzione quadrata, mentre delira altrimenti...
la funzione fill_matrix() prende come primo argomento la matrice, poi gli argomenti successivi saranno le righe della matrice sotto forma di stringhe ogni entrata è separata da uno spazio, in fine l'ultimo argomento è il puntatore NULL.
codice:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
typedef struct Matrix {
int **matrix;
int rows, columns;
}
Matrix ;
Matrix new_matrix( int rows, int columns ){
Matrix matrix;
int i;
matrix.matrix = (int **) malloc ( columns * sizeof(int *) );
for(i=0;i<rows;i++)
matrix.matrix[i] = (int *) malloc( rows * sizeof(int) );
matrix.rows = rows;
matrix.columns = columns;
return matrix;
}
/********************************************************/
void destroy_matrix( Matrix matrix )
{
int i;
for( i=0 ; i<matrix.rows ; i++ )
free(matrix.matrix[i]);
free(matrix.matrix);
}
/********************************************************/
int fill_matrix( Matrix matrix, ... )
{
va_list rows;
int x = 0, y=0, i = 0, j = 0, n = 0;
char * row = malloc( 1024 * sizeof(char));
char * digit = malloc( matrix.columns * sizeof(char) );
int * digits = malloc( matrix.columns * sizeof(int));
va_start(rows, matrix);
//pesca il primo arg dopo matrix
row = va_arg( rows, char* );
//pertanto che vi sono argomenti
while( row != NULL )
{
do{//pertanto che row[i]!=\0
if( isdigit( row[i] ) )
{
digit[j] = row[i] ;
j++;
}
else
{
digit[j] = '\0';
digits[n] = atoi(digit);
n++;
j = 0;
}
i++;
}while( row[i] != '\0');
digit[j] = '\0';
digits[n] = atoi(digit);
for(x=0;x<matrix.columns;x++)
matrix.matrix[y][x] = digits[x]
;
row = va_arg( rows, char* );
n = 0;
j = 0;
i = 0;
y++;
}
va_end(rows);
free(row);
free(digit);
free(digits);
if( y > matrix.rows )
return -1;
else
return 0;
}
/********************************************************/
void print_matrix( Matrix matrix )
{
int x,y;
for( y = 0 ; y < matrix.columns ; y++ )
{
for( x = 0 ; x < matrix.rows ; x++ )
printf("%d ",matrix.matrix[y][x]);
printf("\n");
}
}
/********************************************************/
int main()
{
Matrix matrix = new_matrix(3,4);
if( fill_matrix( matrix, "1 2 3 4", "5 6 7 8", "9 10 11 12", NULL ) == -1 )
perror("error1");
print_matrix( matrix );
destroy_matrix( matrix );
return 0;
}
La funzione mi sembra scritta in maniera molto generale, non capisco perche non venga digerita se la matrice e rettangolare...
Ringrazio tutti coloro che hanno letto il codice!