我怎么可能会创建使用C中的malloc和避免内存问题的矩阵?如何使用C99语法矩阵传递给函数? [英] How may I create a matrix in C using malloc and avoiding memory problems? How I can use C99 syntax to pass the matrix to a function?

查看:89
本文介绍了我怎么可能会创建使用C中的malloc和避免内存问题的矩阵?如何使用C99语法矩阵传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你有关于使用的malloc 功能主治好要分配给矩阵存储空间?

Have you good indications about use of the malloc function to allocate memory space for matrices?

在这些日子里,我看到,在一个坏的方式很多codeRS code矩阵,当它需要使用的malloc 来管理它们。我在错误的时候我这样想呢?

In these days I saw that a lot of coders code matrices in a "bad" way when it needs to use malloc to manage them. Am I in error when I think that?

坏code我的意思的例子如下:

An example of the "bad" code I mean is the following:

int main()
{
    char **row;
    int width=80, height=24, i, j;

    row = malloc(height * sizeof(char *));
    for(i = 0; i < width; i++)
        row[i] = malloc(width * sizeof(char));

    for(i = 0; i < height; i++)
    {
        for(j = 0; j < width; j++)
        {
            row[i][j] = i*j;
        }
    }

    return 0;
}

在code以上,我觉得至少有三个问题:

In the code above I find at least three problems:


  • 它强烈的碎片的记忆。

  • It strongly fragments the memory.

它使用更多的内存

这使得不是连续的,它使用的矩阵的内存。

It makes not contiguous the memory it uses for the matrix.

有人建议我用这个C99语法有趣的方式:

Somebody suggest me the interesting way to use this C99 syntax:

int (*matrix)[columns] = malloc(sizeof(int[rows][columns]));

现在我需要这个变量矩阵传递到下面的函数:

Now I need to pass this variable matrix into the following function:

void print_matrix2(int **m,int r,int c)
{
    int y,x;

    for(y=0;y<r;y++) {
        for(x=0;x<c;x++) {
            printf("(%2d,%2d) = %04d; ",y+1,x+1,m[y][x]);
        }
    }
}

我发现的唯一方法是改变原型:

The only way I've found is to change the prototype:

void print_matrix2(int (*m)[5],int r,int c);

但我想避免的[5]声明,我想能够发送到我的任何功能列的数量我想要!

but I want to avoid the [5] declaration, I want be able to send to my function whatever number of column I want!

如果是,我觉得这C99改进并不彻底解决这个问题,我认为要解决矩阵管理是采用经典的C语言来管理他们最好的和简单的方式!

If that is, I feel this C99 improvement is not a definitive solution to the problem and I think the best and simple way to solve the matrices management is to manage them using the classical C language!

推荐答案

使用的malloc()来分配内存的连续的大块:

Use malloc() to allocate a contiguous chunk of memory:

some_datatype_t* matrix = NULL;
matrix = malloc(nrows * ncols * sizeof(some_datatype_t));
if (!matrix) { 
    perror("malloc failed");
    exit(ENOMEM); 
}

编写一个函数取消引用的单元格:

Write a function to dereference a cell:

some_datatype_t 
get_value_from_matrix_at_index_ij(some_datatype_t* mtx, 
                                  uint32_t ncols, 
                                  uint32_t i, 
                                  uint32_t j) 
{
    return mtx[i + i * (ncols - 1) + j];
}

或者一个setter:

Or a setter:

void
set_value_for_matrix_at_index_ij(some_datatype_t** mtx_ptr,
                                 uint32_t ncols, 
                                 uint32_t i, 
                                 uint32_t j,
                                 some_datatype_t val) 
{
    *mtx_ptr[i + i * (ncols - 1) + j] = val;
}

不要忘了免费()你的矩阵,当你用它做:

Don't forget to free() your matrix when you're done with it:

free(matrix), matrix = NULL;

下面是一个3×4矩阵的例子:

Here's an example of a 3x4 matrix:

    0  1  2  3
  ------------
0 | 0  1  2  3
1 | 4  5  6  7
2 | 8  9 10 11

它有3行4列( NCOLS = 4 )。

在线性的形式,它的细胞是这样的:

In linearized form, its cells look like this:

0 1 2 3 4 5 6 7 8 9 10 11

要在一些零索引行查找一个单元格的内容 I 和列Ĵ,可以计算出指数或地址,取消引用在固定时间:

To lookup a cell's contents at some zero-indexed row i and column j, you can calculate the index or address to dereference in constant time:

{1, 2} = matrix[1 + 1*3 + 2] = matrix[6]
{2, 3} = matrix[2 + 2*3 + 3] = matrix[11]
etc.

如果你想藏起来一些有用的属性到一个清洁套装,你甚至可以换了很多本成一个结构

If you want to hide away some useful attributes into a clean package, you could even wrap a lot of this up into a struct:

typedef struct matrix {
    some_datatype_t* data;
    uint32_t nrows;
    uint32_t ncols;
} matrix_t;

然后你只需初始化和周围的指针传递给 matrix_t 变量:

matrix_t*
init_matrix(uint32_t nrows, uint32_t ncols) 
{
    matrix_t *m = NULL;
    m = malloc(sizeof(matrix_t));
    if (!m) { /* error */ }
    m->data = NULL;
    m->data = malloc(nrows * ncols * sizeof(some_datatype_t));
    if (!m->data) { /* error */ }
    m->nrows = nrows;
    m->ncols = ncols;
    return m;
}

some_datatype_t 
get_value_from_matrix_at_index_ij(matrix_t* mtx,
                                  uint32_t i, 
                                  uint32_t j) 
{
    return mtx->data[i + i * (mtx->ncols - 1) + j];
}

void
set_value_for_matrix_at_index_ij(matrix_t** mtx_ptr,
                                 uint32_t i, 
                                 uint32_t j,
                                 some_datatype_t val) 
{
    (*mtx_ptr)->data[i + i * ((*mtx_ptr)->ncols - 1) + j] = val;
}

void
delete_matrix(matrix_t** m) 
{
    free((*m)->data), (*m)->data = NULL;
    free(*m), *m = NULL;
}

如果你使用对称方阵的工作,你可以利用的对称性和使用一半的内存。有时,只有不到一半的存储器,如果对角的存储可以被删除(例如,举例来说,相关性或其他对称统计分数)。

If you're working with a symmetric square matrix, you can exploit the symmetry and use half the memory. Sometimes, less than half the memory, if storage of the diagonal can be removed (say, for instance, correlation or other symmetric statistical scores).

主要是,这里的想法是要思考如何编写矩阵指数对之间映射的等式(I,J)和一些连续的阵列指数<$ ç$ C> K 。

Mainly, the idea here is to think about how to write an equation that maps between a matrix index pair (i, j) and some contiguous-array index k.

这篇关于我怎么可能会创建使用C中的malloc和避免内存问题的矩阵?如何使用C99语法矩阵传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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