I am doing a code that needs to generate a random matrix, save it in a .txt
and do something with it. The matrix needs to change in dimension and I think the way I declared it is the way that will allow me to deallocate and then allocate it again (if not please let me know).
My problem is the random number generator doesn't work, it saves one number in the file and if I print it it gives two different outputs. It's probably because I am not declaring the matrix well or giving it the value accordingly.
I will leave a picture of the three different outputs it creates, only one makes sense given the range I put rand
to work with (1-9).
I believe the problem is in the usage of the matrix. Is the matrix a pointer in my code? When would I use *
or &
with it?
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
#include <string.h>
int main(){
FILE *f;
int nmatrix=3;
int nmax=nmatrix;
int number, cout, count, count2, i, j, k, p;
srand(time(NULL));
//int C[nmatrix][nmatrix];
//int (*B)[nmatrix][nmatrix] = malloc(nmatrix * nmatrix * sizeof(int));
float **a = malloc(nmatrix * sizeof(float *));
for (p = 0; p < nmatrix; p++) {
a[p]=malloc(nmatrix * sizeof(int));
}
while(nmatrix<=nmax){
// Creation of Matrix
f = fopen("matrix.txt", "w");
for(count = 0; count < nmatrix; count ++){
for(count2 = 0; count2 < nmatrix; count2 ++){
a[count][count2]= (rand()%8)+1;
fprintf(f, "%s%d ", " ", a[count][count2]);
printf(" A1:%d, A2:%d \n", a[count][count2], a[count][count2]);
}
fprintf(f, "%s\n", " ");
}
fclose(f);
nmatrix=nmatrix+1;
/*More code*/
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire