Evening all,
I've written a working code to create a matrix (the size of which is defined by the user) and fill it with random values and print out the result.
Why then am I posting it here? Well whenever I run it, as I press the key to close the programme I get an error message saying my programme has stopped working. Can any one help me with this?
Theres two places I think its occuring but I'm not entirely sure. One place it could be is in my use of pointers (farily new to them) and maybe also in the malloc/free functions
Any help is help
Cheers
Code:
// A programme to create a user defined matrix and fill it with random values
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <malloc.h>
#include <time.h>
//FUNCTIONS
//Function to return a random double in the range [0.0,100.0]
double random()
{
double n,m;
n=rand();
m=100*n/RAND_MAX;
return(m);
}
//Function to populate matrix with random values:
double *rand_matrix(double *mat, int rows, int cols)
{
for (int i=0 ; i<rows ; i++)
{ for (int j=0 ; j<cols ; j++)
{ *(mat+i*rows+j)=random();
}
}
return(mat);
}
//Function to print out a matrix:
void print_matrix(double *mat,int rows,int cols)
{
for (int i=0 ; i<rows ; i++)
{ for (int j=0 ; j<cols ; j++)
{ printf("%5.2lf ",*(mat+i*rows+j));
}
printf("\n");
}
}
int main ()
{
//Before programme starts I must seed the random generator.
srand(time(0));
//initialise variables;
int m,n,err,yesno=0;
double **ptr_rows=0,**user_ptr=0,*elem_ptr=0;
//Take input from the user for the size of the matrix
do
{
printf("Enter the number of Rows and Collumns in the form m n\n>> ");
err=scanf("%d %d",&m,&n);
_flushall();
if ((err!=2)||(m<=0)||(n<=0))
{do
{
printf("\nERROR you must have an integer number of rows and collumns\nEnter the number of Rows and Collumns in the form m n\n>> ");
err=scanf("%d %d",&m,&n);
_flushall();
if ((err==2)&&(m>0)&&(n>0))
break;
}while ((err!=2)||(m<=0)||(n<=0));
}
printf("\nThe size of the matrix you have decided to use is %dx%d\npress 'N' to enter a different size or press any key to continue.\n",m,n);
scanf("%c",&yesno);
_flushall();
}while ((yesno=='N')||(yesno=='n'));
//Allocate memory for this matrix
ptr_rows =(double**) malloc(m*sizeof(double*));
user_ptr=ptr_rows;
for( int i=0 ; i<m ; i++)
{ *user_ptr=(double*)malloc(n*sizeof(double));
elem_ptr=*user_ptr;
for(int j=0 ; j<n ;j++)
*elem_ptr++=1.0;
user_ptr++;
}
user_ptr=ptr_rows;
//Use rand_matrix function to create a ransom Matrix
print_matrix((double*) rand_matrix(*user_ptr,m,n),m,n);
getch();
//free the memory from the matrix
for( int i=0; i<n ; i++);
free(*user_ptr++);
free(ptr_rows);
return (0);
}