#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
#define MALLOC(ptr, size) \\
if(!((ptr) = malloc(size))) { \\
fprintf(stderr, "Insufficient memory"); \\
exit(EXIT_FAILURE);\\
}
#define CALLOC(ptr, n, size) \\
if(!((ptr) = calloc(n, size))){\\
fprintf(stderr, "Insufficient memory"); \\
exit(EXIT_FAILURE);\\
}
#define REALLOC(ptr, size) \\
if(!((ptr) = realloc(ptr, size))){\\
fprintf(stderr, "Insufficient memory"); \\
}
int** make2dArray(int rows, int cols);
void add(int **a, int **b, int **c, int rows, int cols);
void mult(int **a, int **b, int **c, int rows);
void main(int argc, char* argv[])
{
int i, j;
int n;
int **A, **B, **C;
n = atoi(argv[1]);
A = make2dArray(n, n);
B = make2dArray(n, n);
C = make2dArray(n, n);
srand((unsigned)time(NULL));
for(i = 0; i < n; ++i){
for(j = 0; j < n; ++j){
A[i][j] =rand() % 10;
B[i][j] =rand() % 10;
}
}
mult(A, B, C, n);
for(i = 0; i < n; ++i){
printf("[ ");
for(j = 0; j < n; ++j){
printf("%3d ", A[i][j]);
}
printf("] ");
if(i == ((int)n/2)) printf(" + ");
else printf(" ");
printf("[ ");
for(j = 0; j < n; ++j){
printf("%3d ", B[i][j]);
}
printf("]");
if(i == ((int)n/2)) printf(" = ");
else printf(" ");
printf("[ ");
for(j = 0; j < n; ++j){
printf("%3d ", C[i][j]);
}
printf("]\\n");
}
}
int** make2dArray(int rows, int cols)
{
int **x, i;
CALLOC(x, rows, rows * sizeof(*x));
for(i = 0; i < rows; ++i)
CALLOC(x[i], cols, cols * sizeof(**x));
return x;
}
void add(int **a, int **b, int **c, int rows, int cols)
{
int i, j;
for(i = 0; i < rows; ++i){
for(j = 0; j < cols; ++j){
c[i][j] = a[i][j] + b[i][j];
}
}
}
void mult(int **a, int **b, int **c, int rows)
{
int i, j, k;
for(i = 0; i < rows; i++){
for(j = 0; j < rows; j++){
for(k = 0; k < rows; k++){
c[i][j] += a[i][k] * b[k][j];
}
}
}
}