Hey I'm writing a programme to create a random matrix and print it to a file. But when I run it just shuts the programmes down. No errors no warnings nothing.
I'm using Dev C++ and when I debug I get an error "access violation (segmentation violation).
I've tested the file out put and it works I've also tested the print_matrix function and it works.
The issue lies in the rand_matrix function, I've done a bit of research and I think the issue is indexing outside an array or miss-indexing
Any help is help
Thanks in Advance
Code:
#include <stdio.h>#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#include <conio.h>
typedef struct matrep {
unsigned rows, columns;
double*data;
} MATRIX;
/////////////////////////////////////////////////////////
double random()
{
static int seeded = 0;
double val ;
if ( !seeded )
{
srand( time(NULL) ) ;
seeded = 1;
}
val = ((double)rand())/ (double)RAND_MAX * 100.0 ;
return val ;
}
////////////////////////////////////////////////////////
MATRIX*rand_matrix( struct matrep*mat )
{
for ( int i=0; i < mat->rows; i++ )
{
for ( int j=0; j < mat->columns; j++ )
{
*(mat->data)++ = random() ;
}
}
return mat ;
}
//////////////////////////////////////////////////////////
void print_matrix(struct matrep*mat )
{
int i, j ;
if ( (mat->data)==0 || (mat->rows)==0 || (mat->columns)==0 )
{
printf("Empty matrix\n" );
return ;
}
printf( "\n\nMatrix of dimensions %d x %d\n\n", mat->rows, mat >columns) ;
for ( i=0; i < mat->rows; i++ )
{
for ( j=0; j < mat->columns; j++ )
{
printf("\t%1.2lf", *(mat->data)++ );
}
printf("\n") ;
}
}
///////////////////////////////////////////////////////////
void matrix_write(struct matrep*mat,FILE *fp)
{
fprintf(fp,"rows = %d, columns = %d \n",mat->rows,mat->columns);
for ( int i=0; i < mat->rows; i++ )
{
for ( int j=0; j < mat->columns; j++ )
{
fprintf(fp, "\t%.2lf", *(mat->data)++ );
}
fprintf(fp, "\n" ) ;
}
}
int main()
{
MATRIX mat;
mat.rows=4;
mat.columns=5;
MATRIX *ptr;
ptr=&mat;
rand_matrix(ptr);
print_matrix(ptr);
FILE *fp;
char file[80];
printf("enter file name: ");
gets(file);
if((fp=fopen(file,"w"))==NULL)
{
printf("Cannot open file %s",file);
getch();
exit(1);
}
matrix_write(&mat,fp);
fclose(fp);
printf("\nOperations complete. Hit any key to exit");
getch();
return (0);
}