document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <time.h>
  5.  
  6. #define SWAP(x, y, t)   ((t) = (x), (x) = (y), (y) = (t))
  7.  
  8. #define MALLOC(ptr, size)  \\
  9.   if(!((ptr) = malloc(size))) { \\
  10.     fprintf(stderr, "Insufficient memory"); \\
  11.     exit(EXIT_FAILURE);\\
  12.   }
  13.  
  14. #define CALLOC(ptr, n, size) \\
  15.   if(!((ptr) = calloc(n, size))){\\
  16.     fprintf(stderr, "Insufficient memory"); \\
  17.     exit(EXIT_FAILURE);\\
  18.   }
  19.  
  20. #define REALLOC(ptr, size) \\
  21.   if(!((ptr) = realloc(ptr, size))){\\
  22.     fprintf(stderr, "Insufficient memory"); \\
  23.   }
  24.  
  25. int** make2dArray(int rows, int cols);
  26. void add(int **a, int **b, int **c, int rows, int cols);
  27. void mult(int **a, int **b, int **c, int rows);
  28. void transpose_squared(int **a, int rows);
  29. void transpose_non_squared(int **a, int **b, int rows, int cols);
  30.  
  31. void main(int argc, char* argv[])
  32. {
  33.   int i, j;
  34.   int rows;
  35.   int **A, **B;
  36.  
  37.   if(argc != 2){
  38.     fprintf(stderr, "Usage: ./ex1-5 [rows]\\n");
  39.     exit(-1);
  40.   }
  41.  
  42.   rows = atoi(argv[1]);
  43.  
  44.   A = make2dArray(rows, rows);
  45.  
  46.   srand((unsigned)time(NULL));
  47.   printf("Before transpose\\n");
  48.   for(i = 0; i < rows; ++i){
  49.     printf("[ ");
  50.     for(j = 0; j < rows; ++j){
  51.       A[i][j] =rand() % 10;
  52.       printf("%3d ", A[i][j]);
  53.     }
  54.     printf("]\\n");
  55.   }
  56.  
  57.   printf("\\nAfter transpose\\n");
  58.   transpose_squared(A, rows);
  59.   for(i = 0; i < rows; ++i){
  60.     printf("[ ");
  61.     for(j = 0; j < rows; ++j){
  62.       printf("%3d ", A[i][j]);
  63.     }
  64.     printf("]\\n");
  65.   }
  66. }
  67.  
  68. int** make2dArray(int rows, int cols)
  69. {
  70.   int **x, i;
  71.  
  72.   CALLOC(x, rows, rows * sizeof(*x));
  73.  
  74.   for(i = 0; i < rows; ++i)
  75.     CALLOC(x[i], cols, cols * sizeof(**x));
  76.   return x;
  77. }
  78.  
  79. void add(int **a, int **b, int **c, int rows, int cols)
  80. {
  81.   int i, j;
  82.  
  83.   for(i = 0; i < rows; ++i){
  84.     for(j = 0; j < cols; ++j){
  85.       c[i][j] = a[i][j] + b[i][j];
  86.     }
  87.   }
  88. }
  89.  
  90. void mult(int **a, int **b, int **c, int rows)
  91. {
  92.   int i, j, k;
  93.   for(i = 0; i < rows; i++){
  94.     for(j = 0; j < rows; j++){
  95.       for(k = 0; k < rows; k++){
  96.         c[i][j] += a[i][k] * b[k][j];
  97.       }
  98.     }
  99.   }
  100. }
  101.  
  102. void transpose_squared(int **a, int rows)
  103. {
  104.   int i, j, tmp;
  105.   for(i = 0; i < rows - 1; i++){
  106.     for(j = i + 1; j < rows; j++){
  107.       SWAP(a[i][j], a[j][i],tmp);
  108.     }
  109.   }
  110. }
');