Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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 transpose_squared(int **a, int rows);
- void transpose_non_squared(int **a, int **b, int rows, int cols);
- void main(int argc, char* argv[])
- {
- int i, j;
- int rows, cols;
- int **A, **B;
- if(argc != 3){
- fprintf(stderr, "Usage: ./ex1-5 [rows]\n");
- exit(-1);
- }
- rows = atoi(argv[1]);
- cols = atoi(argv[2]);
- A = make2dArray(rows, cols);
- B = make2dArray(cols, rows);
- srand((unsigned)time(NULL));
- printf("Before transpose\n");
- for(i = 0; i < rows; ++i){
- printf("[ ");
- for(j = 0; j < cols; ++j){
- A[i][j] =rand() % 10;
- printf("%3d ", A[i][j]);
- }
- printf("]\n");
- }
- printf("\nAfter transpose\n");
- transpose_non_squared(A, B, rows, cols);
- for(i = 0; i < cols; ++i){
- printf("[ ");
- for(j = 0; j < rows; ++j){
- printf("%3d ", B[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];
- }
- }
- }
- }
- void transpose_squared(int **a, int rows)
- {
- int i, j, tmp;
- for(i = 0; i < rows - 1; i++){
- for(j = i + 1; j < rows; j++){
- SWAP(a[i][j], a[j][i],tmp);
- }
- }
- }
- void transpose_non_squared(int **a, int **b, int rows, int cols)
- {
- int i,j, tmp;
- for(i = 0; i < cols; i++){
- for(j = 0; j < rows; j++){
- b[i][j] = a[j][i];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment