Skip to content

Instantly share code, notes, and snippets.

@nilbot
Created February 17, 2017 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilbot/d6d413be33bffba6835e14e909647420 to your computer and use it in GitHub Desktop.
Save nilbot/d6d413be33bffba6835e14e909647420 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
void printMatrix(double** m, int n) {
printf("\n\n");
int i = 0;
int j = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
printf("%lf ", m[i][j]);
}
printf("%lf\n", m[i][n - 1]);
}
printf("\n");
}
int main(void) {
int n;
int** A;
int** B;
int i = 0;
int j = 0;
// input foramt:
// 1st line 1 number N = dim(A) = dim(B) = dim(C)
// then N lines of N numbers separated by space for A
// then N lines of N numbers separated by space for B
printf("Please enter matrix dimension n : ");
scanf("%d", &n);
// allocate memory for the matrices
// note that for each matrix there
// are only two memory allocations
///////////////////// Matrix A //////////////////////////
A = (int**)malloc(n * sizeof(int*));
A[0] = (int*)malloc(n * n * sizeof(int));
if (!A) {
printf("memory failed \n");
exit(1);
}
for (i = 1; i < n; i++) {
A[i] = A[0] + i * n;
if (!A[i]) {
printf("memory failed \n");
exit(1);
}
}
///////////////////// Matrix B //////////////////////////
B = (int**)malloc(n * sizeof(int*));
B[0] = (int*)malloc(n * n * sizeof(int));
if (!B) {
printf("memory failed \n");
exit(1);
}
for (i = 1; i < n; i++) {
B[i] = B[0] + i * n;
if (!B[i]) {
printf("memory failed \n");
exit(1);
}
}
// initialize the matrices
// we can also create random matrices using the rand() method from the
// math.h library
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
int d1 = rand()%99;
int d2 = rand()%99;
A[i][j] = d1;
B[i][j] = d2;
}
}
printMatrix(A, n);
printMatrix(B, n);
// deallocate memory
free(A[0]);
free(A);
free(B[0]);
free(B);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment