保存2D动态数组(矩阵)以进行全局访问c [英] Save 2D Dynamic Array (Matrix) for Global Access c

查看:54
本文介绍了保存2D动态数组(矩阵)以进行全局访问c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将使用函数填充的2D数组保存到全局内存.处理了许多矩阵,成功后,需要保存正确的矩阵以访问众多功能.

I am trying to save a 2D Array that is populated using a function to global memory. Many matrices are processed and upon success, the correct Matrix needs to be saved for access to numerous functions.

当前,函数中的矩阵是使用以下代码动态分配的:

Currently, the matrix within the function is dynamically allocated with the following code:

int **M = malloc(m * sizeof(int *));
for(i = 0; i < m; i++)
    M[i] = malloc(n * sizeof(int));

我声明了一个全局变量(int ** M_save).在主程序中,当需要保存矩阵时,使用相同的过程初始化全局数组:

I have a global variable declared (int **M_save). In the main program when the matrix needs to be saved, the global array is initialized using the same procedure:

**M_save = malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
    M_save[i] = malloc(n * sizeof(int));

然后通知该函数在释放其内存之前需要保存矩阵,并且该函数使用以下过程进行保存:

The function is then notified that it needs to save the matrix before it frees its memory and the following procedure is used in the function to save:

if(saveMatrix == 1) {
for(i = 0; i < m; i++) {
    for(j = 0; j < n; j++) {
        M_save[i][j] = M[i][j];
    }
}

}

运行程序时,在复制值时收到分段错误(M_save [i] [j] = M [i] [j]).我不确定自己在做什么错.

When running the program I receive a segmentation fault when the values are being copied (M_save[i][j] = M[i][j]). I am not sure what I am doing wrong.

我检查以确保两个数组的m和n大小都相同,并在使用完矩阵后使用以下代码将它们从内存中释放出来:

I checked to make sure than m and n are the same size for both array and after I am done using the matrices they are freed from memory with the following code:

for(i = 0; i < m; i++) {
    free(M[i]);
}
free(M);

推荐答案

该解决方案非常简单.矩阵被全局定义为

The solution turned out to be very simple. The matrix was defined globally as

int **M_save;

使用以下方法为我分配了它:

I was assigned it in main using the following:

**M_save = malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
    M_save[i] = malloc(n * sizeof(int));

相反,我 应该一直使用

Instead I should have been using

M_save = malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
    M_save[i] = malloc(n * sizeof(int));

这篇关于保存2D动态数组(矩阵)以进行全局访问c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆