C语言创建二维数组(矩阵)方法

发表时间: 2017-04-26作者: 何景松 0 32

    C语言创建二维数组(矩阵)方法

    以前刚学C语言的时候, 想要手动生成二维数组,就为每一行申请一次内存。如果中间出现申请失败, 还得回滚操作, 将申请的内存全部释放。非常容易出错。当时就想有没有只申请一次内存, 就可以把问题解决。 还真有。。。

    大致流程是这样

    源码如下

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXROWS 10
    #define MAXCOLS 10
    
    /**
     * [create_matrix 创建矩阵(二维数组)]
     * @param cols         [列数]
     * @param rows         [行数]
     * @param element_size [元素大小]
     * return p            [指向二维数组指针]
     */
    void** create_matrix(const unsigned int cols, const unsigned int rows, const unsigned int element_size) {
        int i = 0;
        void** p = NULL;
        unsigned int header_size = 0;
        unsigned int line_size = 0;
        unsigned int total_size = 0;
    
        if ( cols == 0 || rows == 0 || element_size == 0 ) {
            goto RET;
        }
    
        header_size = sizeof(void*) * rows;
        line_size = element_size * cols;
        total_size = header_size + rows * line_size;
        p = (void **)malloc( total_size );
        if ( p == NULL ) {
            goto RET;
        }
    
        p[0] = (void *)p + header_size;
        while( ++i < rows ) {
            p[i] = p[i-1] + line_size;
        }
    
    RET:
        return p;
    }
    
    /**
     * [free_matrix 释放生成矩阵所生成的内存]
     * @param p [指向矩阵的指针]
     */
    void free_matrix(void* p) {
        free(p);
    }
    
    int main(int argc, char const *argv[])
    {
        unsigned int** p = NULL;
        unsigned int i = 0;
        unsigned int j = 0;
    
        p = (unsigned int **)create_matrix(MAXROWS, MAXCOLS, sizeof(unsigned int));
        if ( p == NULL ) return 1;
    
        for ( i=0; i<MAXROWS; i++ ) {
            for ( j=0; j<MAXCOLS; j++ ) {
                p[i][j] = i * j;
            }
        }
    
        for ( i=0; i<MAXROWS; i++ ) {
            for ( j=0; j<MAXCOLS; j++ ) {
                printf("%d - %d: %d\r\n", i, j, p[i][j]);
            }
        }
    
        if ( p != NULL )
            free_matrix((void*)p);
        return 0;
    }