我有一个动态分配的矩阵,我想创建另一个矩阵,它是第一个矩阵,但旁边有另一个副本。例如,我有矩阵:
11 22
我的新矩阵将是:
1 1 1 1 2 2 2 2
我怎样才能连接它们?这是我在 C 中的代码:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int **create_matrix(int row, int col)
{
int **matrix = malloc(sizeof (int*)*row);
int i;
for (i = 0; i < row; i++)
{
matrix[i] = malloc(sizeof (int)*col);
}
return matrix;
}
void matrix_input(int **matrix, int row, int col)
{
int i, j;
printf("enter the elements of the matrix:\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
scanf("%d", &matrix[i][j]);
}
}
}
int **extend_matrix(int **matrix, int row, int col)
{
int k, j;
int i;
int **extend_matrix = malloc(sizeof (int*)*row);
for (k = 0; k < row + row; k++)
{
extend_matrix[k] = malloc(sizeof (int)*col);
}
extend_matrix = matrix;
extend_matrix = (int**) realloc(extend_matrix, (row + row) * sizeof (int*));
extend_matrix[j] = matrix[j];
for (i = 0; i < row; i++)
{
extend_matrix[k] = matrix[i];
}
}
void print_matrix(int **matrix, int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf(" %d ", matrix[i][j]);
}
printf("\n");
}
}
void print_extend_matrix(int **extend_matrix, int row, int col)
{
int k, j;
for (k = 0; k < row + row; k++)
{
for (j = 0; j < col; j++)
{
printf("%d", extend_matrix[k][j]);
}
printf("\n");
}
}
int main(void)
{
int **matrix;
int **extend_matrix;
int row, col;
printf("enter the number of rows of cols:");
scanf("%i%i", &row, &col);
matrix = create_matrix(row, col);
matrix_input(matrix, row, col);
print_matrix(matrix, row, col);
print_extend_matrix(extend_matrix, row, col);
getch();
return 0;
}