本文介绍了功能动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int **Matrix_B1;

Matrix_B1 = (int**)malloc(RowB*(sizeof(int*)));

for (int p=0; p<RowB; p++)
{
    Matrix_B1[p] = (int*)malloc(ColumnB*(sizeof(int)));
}

我如何创建一个函数来在C执行动态内存分配?

How do I create a function to perform dynamic memory allocation in c ?

我有很多这样的矩阵,我不想要保持写同样的事情。

I have lots of matrices like this and I don't want to keep writing the same thing.

推荐答案

只需使用功能,你通常会。还要记住的尺寸。还记得释放时,你就大功告成了!

Just use functions as you would normally. Remember to keep track of the dimensions. Also remember to free when you're done!

#include <stdlib.h>

int **Create2x2Matrix(int rowB, int columnB)
{
    int **matrix = (int**)malloc(rowB*(sizeof(int*)));
    for (int p=0; p<rowB; p++)
    {
        matrix[p] = (int*)malloc(columnB*(sizeof(int)));
    }
    return matrix;
}

void Destroy2x2Matrix(int **matrix, int rowB)
{
    for (int p=0; p<rowB; p++)
    {
        free(matrix[p]);
    }
    free(matrix);
}

int main()
{
    int rowB = 10;
    int columnB = 11;
    int **matrix_B1 = Create2x2Matrix(rowB, columnB);
    Destroy2x2Matrix(matrix_B1, rowB);
    return 0;
}

这篇关于功能动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-22 01:46