Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ConsoleApplication23.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include "stdlib.h"
- #include "stdio.h"
- #include "iostream"
- #include "iomanip"
- using namespace std;
- int getRandomInt(int min, int max);
- int** allocMemory(int rows, int cols);
- int** randomMatrix(int rows, int cols, int min, int max);
- void displayMatrix(int **m, int rows, int cols);
- void freeMemory(int**matrix, int rows);
- int** addMatrices(int **m1, int **m2,int rows, int cols);
- int main()
- {
- int **matrix1 = NULL;
- int **matrix2 = NULL;
- int **matrix3 = NULL;
- int rows, cols, min, max;
- cout << "wymiary: ";
- cin >> rows >> cols;
- cout << endl << "min max: ";
- cin >> min >> max;
- matrix1 = randomMatrix(rows, cols, min, max);
- matrix2 = randomMatrix(rows, cols, min, max);
- matrix3 = addMatrices(matrix1, matrix2, rows, cols);
- displayMatrix(matrix1, rows, cols);
- displayMatrix(matrix2, rows, cols);
- displayMatrix(matrix3, rows, cols);
- freeMemory(matrix1, rows);
- freeMemory(matrix2, rows);
- freeMemory(matrix3, rows);
- return 0;
- }
- int getRandomInt(int min, int max)
- {
- return rand() % (max - min + 1) + min;
- }
- int** allocMemory(int rows, int cols)
- {
- int **temp = (int**)malloc(rows * sizeof(int));
- if (temp == NULL)return NULL;
- for (int i = 0;i < rows;i++)
- {
- temp[i] = (int*)malloc(cols * sizeof(int));
- if (temp[i] == NULL)return NULL;
- }
- return (int**)realloc(temp, rows*cols * sizeof(int));
- }
- void freeMemory(int**matrix, int rows)
- {
- for (int i = 0;i < rows;i++)
- {
- free(matrix[i]);
- }
- free(matrix);
- }
- int** randomMatrix(int rows, int cols, int min, int max)
- {
- int **temp = allocMemory(rows, cols);
- if (temp == NULL)return NULL;
- for (int i = 0;i < rows;i++)
- {
- for (int x = 0;x < cols;x++)
- {
- temp[i][x] = getRandomInt(min, max);
- }
- }
- return (int**)realloc(temp, rows*cols * sizeof(int));
- }
- void displayMatrix(int **m, int rows, int cols)
- {
- if (m == NULL)return;
- int cellSize = 3;
- for (int i = 0;i < rows;i++)
- {
- for (int x = 0;x < cols;x++)
- {
- cout << setw(cellSize);
- cout << m[i][x];
- }
- cout << endl;
- }
- cout << endl;
- }
- int** addMatrices(int **m1, int **m2, int rows, int cols)
- {
- if (m1 == NULL || m2 == NULL)return NULL;
- int **temp = allocMemory(rows, cols);
- for (int i = 0;i < rows;i++)
- {
- for (int x = 0;x < cols;x++)
- {
- temp[i][x] = m1[i][x] +m2[i][x];
- }
- }
- return (int**)realloc(temp, rows*cols * sizeof(int));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement