malloc in C, but use multi-dimensional array syntax

后端 未结 8 996
失恋的感觉
失恋的感觉 2020-12-04 22:59

Is there any way to malloc a large array, but refer to it with 2D syntax? I want something like:

int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICV         


        
8条回答
  •  無奈伤痛
    2020-12-04 23:35

    Working from Tim's and caf's answers, I'll leave this here for posterity:

    #include 
    #include 
    
    void Test0() {
        int                             c, i, j, n, r;
        int                             (*m)[ 3 ];
    
        r = 2;
        c = 3;
    
        m = malloc( r * c * sizeof(int) );
    
        for ( i = n = 0; i < r; ++i ) {
            for ( j = 0; j < c; ++j ) {
                m[ i ][ j ] = n++;
                printf( "m[ %d ][ %d ] == %d\n", i, j, m[ i ][ j ] );
            }
        }
    
        free( m );
    }
    
    void Test1( int r, int c ) {
        int                             i, j, n;
    
        int                             (*m)[ c ];
    
        m = malloc( r * c * sizeof(int) );
    
        for ( i = n = 0; i < r; ++i ) {
            for ( j = 0; j < c; ++j ) {
                m[ i ][ j ] = n++;
                printf( "m[ %d ][ %d ] == %d\n", i, j, m[ i ][ j ] );
            }
        }
    
        free( m );
    }
    
    void Test2( int r, int c ) {
        int                             i, j, n;
    
        typedef struct _M {
            int                         rows;
            int                         cols;
    
            int                         (*matrix)[ 0 ];
        } M;
    
        M *                             m;
    
        m = malloc( sizeof(M) + r * c * sizeof(int) );
    
        m->rows = r;
        m->cols = c;
    
        int                             (*mp)[ m->cols ] = (int (*)[ m->cols ]) &m->matrix;
    
        for ( i = n = 0; i < r; ++i ) {
            for ( j = 0; j < c; ++j ) {
                mp[ i ][ j ] = n++;
                printf( "m->matrix[ %d ][ %d ] == %d\n", i, j, mp[ i ][ j ] );
            }
        }
    
        free( m );
    }
    
    int main( int argc, const char * argv[] ) {
        int                             cols, rows;
    
        rows = 2;
        cols = 3;
    
        Test0();
        Test1( rows, cols );
        Test2( rows, cols );
    
        return 0;
    }
    

提交回复
热议问题