c - Matrix Output is garbage data -
so, i'm trying here printout matrix or array. now, input file has set of integers. problem when output matrix it's bunch of random numbers. it's single digits don't think it's address associated pointers. first integer in input file suppose array length or call here "col".
#define max 10 int main() { int col,row; /* array dimensions */ int i,j,k; /* counter variables */ int n; /* temporary variable elements*/ int temp[max*max]; /* temporary array row counting */ int counter=0; /* counter variable number of rows */ int matrix[max][max]; /* input matrix */ file *in; /* pointer input file of elements */ /* input */ printf("\nplease enter desired number of columns , elements of matrix.\n"); fscanf(in,"%d",&temp[0]); /* enter matrix length */ col = temp[0]; /* assign integer value col variable */ if( col < 1 || col > max){ /* standard error invalid input */ fprintf(stderr,"\ninvalid length\n"); exit(1); } /* processing */ while(fscanf(in,"%d",&n)!=eof){ /* determine number of rows */ temp[counter++]=n; } if(counter % col == 0){ /* standard error exceeding/lesser amount of input*/ fprintf(stderr,"\ninvalid amount of input\n"); exit(1); /* quits out program error */ } else{ row = counter / col; /* determine number of rows */ } for(i = 0; < row; i++){ /* read elements */ for(j = 0; j < col; j++){ for(k=1; k < counter; k++){ matrix[i][j] = temp[k]; } } } /* output */ fprintf(stdout,"\nhere matrix:"); /* matrix header */ for(i=0; < row; i++){ /* print out input matrix */ fprintf(stdout,"\n"); for(j = 0; j < col; j++){ fprintf(stdout,"%3d ",matrix[i][j]); } } fprintf(stdout,"\n"); the input: 2 1 2 3 4 5 6
the output: please enter desired number of columns , elements of matrix.
here matrix: 6 6 6 6 6 6 ^ don't know if our unix system telling me myself or what. i'm scared now.
edit: okay, removed comments between lines of code. edit: compiled , tested program.
problem here, every matrix i,j same k.
for(i = 0; < row; i++){ /* read elements */ for(j = 0; j < col; j++){ for(k=1; k < counter; k++){ matrix[i][j] = temp[k]; } } } change to, int count=0; for(i = 0; < row; i++){ /* read elements */ for(j = 0; j < col; j++){ count++; matrix[i][j] = temp[count]; } }
Comments
Post a Comment