gpt4 book ai didi

连接 2 个矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:49 24 4
gpt4 key购买 nike

我有一个动态分配的矩阵,我想创建另一个矩阵,它是第一个矩阵,但旁边有另一个副本。例如,我有矩阵:

1122

My new matrix will be:

1 1 1 12 2 2 2

How can I concatenate them? This is my code in 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;
}

最佳答案

尽管@NPE 向您建议了一个更好的方法。如果要在extend_matrix()中分配内存

代码错误(阅读评论)

int **extend_matrix = malloc(sizeof (int*)*row);
^ on row
for (k = 0; k < row + row; k++)
^ where as loop is for row + row
{
extend_matrix[k] = malloc(sizeof (int)*col); // So this cause an error,
// segment-fault
}

其次,你复制内存的概念是错误的:

 extend_matrix = matrix;  

在这一行中,您将 matrix 分配给 extend_matrix 这是错误的。您需要在此处循环将每个元素从 matrix[][] 复制到 extend_matrix[][]。 (但首先纠正你的内存分配代码)

关于连接 2 个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15197135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com