Code:
void alloc(int*** matrix, const int lin, const int col) {
*matrix = (int**)malloc(sizeof(int*) * lin);
if (*matrix == NULL) {
printf("Error");
exit(1);
}
for (int i = 0;i < lin;i++) {
(*matrix)[i] = (int*)malloc(sizeof(int) * col);
if ((*matrix)[i] == NULL) {
printf("Error");
exit(1);
}
}
for (int i = 0;i < lin;i++)
for (int j = 0;j < col;j++)
{
(*matrix)[i][j] = i + j;
}
}
int** copy(int** matrix, const int lin, const int col) {
int** buffer;
alloc(&buffer, lin, col);
for (int i = 0;i < lin;i++)
for (int j = 0;j < col;j++)
{
buffer[i][j] = matrix[i][j];
}
return buffer;
}
void reall(int*** matrix1,const int lin1,const int col1, int** matrix2,
const int lin2, const int col2) {
if (lin1 > lin2)
{
for (int i = lin1 - 1;i >= lin2;i--)
{
free((*matrix1)[i]);
}
int** temp1 = (int**)realloc(*matrix1, sizeof(int*) * lin2);
if (temp1== NULL) {
printf("Error");
exit(1);
}
*matrix1 = temp1;
}
if (col1 > col2)
{
for (int i = 0;i < lin2;i++)
{
int* temp2 = (int*)realloc((*matrix1)[i], sizeof(int) *
col2);
if (temp2 == NULL) {
printf("Error");
exit(1);
}
(*matrix1)[i] = temp2;
}
}
if (col1 < col2)
{
for (int i = 0;i < lin2;i++)
{
int* temp2 = (int*)realloc((*matrix1)[i], sizeof(int) *
col2);
if (temp2 == NULL) {
printf("Error");
exit(1);
}
(*matrix1)[i] = temp2;
}
for (int j = 0;j < lin2;j++)
{
for (int i = col1;i < col2;i++)
{
(*matrix1)[j][i] = 0;
}
}
}
if (lin1 < lin2)
{
int** temp1 = (int**)realloc(*matrix1, sizeof(int*) * lin2);
if (temp1 == NULL) {
printf("Error");
exit(1);
}
*matrix1 = temp1;
for (int i = lin1;i < lin2;i++) {
(*matrix1)[i] = (int*)malloc(sizeof(int) * col2);
if ((*matrix1[i]) == NULL) {
printf("Error");
exit(1);
}
}
for (int j = lin1;j < lin2;j++)
{
for (int i = 0;i < col2;i++)
{
(*matrix1)[j][i] = 0;
}
}
}
for (int i = 0;i < lin2;i++)
for (int j = 0;j < col2;j++)
(*matrix1)[i][j] = matrix2[i][j];
}
int main() {
int** matrix1, ** matrix2, ** twin;
int n1, m1, n2, m2;
printf("Number of lines for Ist matrix:");
scanf("%d", &n1);
printf("Number of collums for Ist matrix:");
scanf("%d", &m1);
printf("Number of lines for IInd matrix:");
scanf("%d", &n2);
printf("Number of collums for IInd matrix:");
scanf("%d", &m2);
alloc(&matrix1, n1, m1);
alloc(&matrix2, n2, m2);
twin = copy(matrix1, n1, m1);
reall(&matrix1, n1, m1, matrix2, n2, m2);
reall(&matrix2, n2, m2, twin, n1, m1);
for (int i = 0;i < n2;i++)
{
for (int j = 0;j < m2;j++)
{
printf("%d ", matrix1[i][j]);
}
printf("\n");
}
printf("\n\n");
for (int i = 0;i < n1;i++)
{
for (int j = 0;j < m1;j++)
{
printf("%d ", matrix2[i][j]);
}
printf("\n");
}
for (int i = 0; i < m1; i++)
free(twin[i]);
free(twin);
for (int i = 0; i < m2; i++)
free(matrix1[i]);
free(matrix1);
for (int i = 0; i < m1; i++)
free(matrix2[i]);
free(matrix2);
}