I have an assignment to create two randomly generated matrices of size n
(where n
= 4, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192) and multiply these matrices.
I am creating the matrices using malloc
. I'm using just long** intCreateMatrix(n)
function to create both the matrices A
and B
. This function returns a pointer to the matrix. Another function
long** intInitializeMatirx(a,n)
is used to initialize the matrix with random values.
When I call these functions for two different matrices it prints the same contents of matrix for both the matrices.The code is given below:
void intAlgo(int n,int algo){
long **a;
long **b;
long **c;
a = intCreateMatrix(n);
printf("Matrix A:\n");
a = intInitializeMatrix(a,n);
b = intCreateMatrix(n);
printf("Matrix B:\n");
b = intInitializeMatrix(b,n);
}
long** intCreateMatrix(int n){
long **arr;
int i,j;
arr = (long **)malloc(n * sizeof(long *));
for (i=0; i<n; i++)
arr[i] = (long *)malloc(n * sizeof(long));
return arr;
}
long** intInitializeMatrix(long **arr,int n){
int i,j;
srand(time(0));
for(i=0;i<n;i++){
for(j=0;j<n;j++)
arr[i][j] = rand()%10;
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
printf("%ld ",arr[i][j]);
printf("\n");
}
printf("\n");
return arr;
free (arr);
}
intAlgo
is the function that calls the createMatrix
and Initialises matrix.
CreateMAtrix
takes n as input and returns a pointer to the matrix created using malloc
.
InitialiseMatrix
initializes the matrix using rand function and prints the matrix and returns the matrix.
When I execute it a
and b
should have different values
but they have the same values example I'm getting these values for Matrix A
and `B? :
Matrix A
:
0 7 2 3
0 6 3 1
7 2 0 2
6 3 2 6
Matrix B
:
0 7 2 3
0 6 3 1
7 2 0 2
6 3 2 6
These two matrices should be different I'm not sure where I am going wrong. Could you please guide me?