c - 在 C 中扩展矩阵

标签 c matrix malloc realloc

我在 C 中有一个矩阵,我想创建另一个比第一个矩阵有双行的矩阵。那些添加的行我想要第一个矩阵的值,但符号改变了。我想了解动态分配,但我不明白我哪里错了。编译器说的错误是:"invalid conversion from void* to int*" 。这是我的代码:

#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
int *extend_matrix=NULL;
int *matrix=NULL;
int *negative_matrix=NULL;
int main(void)
{
    int i,j,m,n;
    printf("Enter the number of rows and columns of  matrix\n");
    scanf("%d%d", &m, &n);
    int *matrix = (int *)malloc(m * n * sizeof(int));
    int *negative_matrix=(int*)malloc(m*n*sizeof(int));
    printf("Enter the elements of first matrix\n");
    for (  i = 0 ; i < m ; i++ )
        for ( j = 0 ; j < n ; j++ )
            scanf("%d", &matrix[i][j]);
    for(i = 0 ; i < m ; i++)
        for(j = 0 ; j < n ; j++)
            printf("the matrix is: \n",matrix[i][j]);
    negative_matrix=-matrix[i][j];
    for(i=0;i<m+m;i++)
        extend_matrix[i]=realloc(matrix[i],sizeof(int)*(m+m));
    for(j=0;j<n;j++)
        extend_matrix[j]=realloc(matrix[j],sizeof(int)*n);
    extend_matrix[i][j]=matrix[i][j]+negative_matrix[i][j];//how to concatenate them?
    getch();
    return 0;
}

最佳答案

看来你有点糊涂了。让我写一个简短的示例代码

编辑: 好的,去吧here

在那里你会找到我的例子。我还没有完成它,只是就如何完成它提供了意见。

也请注意:

从第 66 行到第 68 行,我们有这段代码:

for (i = 0; i < rows; i++){
    free(first_matrix[i]);
}

这是因为我们矩阵的每个元素都是一个指针,它们都指向一个分配在堆上的数组。所以,如果你刚刚释放 first_matrix,像这样:

free(first_matrix);

你只会从堆上它自己的内容中释放 first_matrix(而不是它的每个元素之一)

关于c - 在 C 中扩展矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191017/

相关文章:

c - 递归、全局变量和 OpenMP

c - PETSc - MatLUFactor - 不支持此对象类型的此操作

c - 我如何将字符串拆分为标记并将标记存储在不同的变量中,C 语言

c - 外部变量VS header 声明

python - 将字典转换为方阵

algorithm - 谜语: How to change matrix color?

c++ - 将二维数组作为函数参数并返回二维数组作为函数的返回类型

C Grid 使用指针和 Malloc

c++ - CPP_TEST.exe : 0xC00000FD: Stack overflow 中 0x7604c128 处未处理的异常

c++ - 编程原理与实践第27章侵入式列表错误?