在C中打印二维数组

时间:2014-09-20 12:39:04

标签: c multidimensional-array

我想打印一个二维数组,我从另一个方法得到,参见代码:

int** getPrint(){
    const int EIGHT[7][5] = {
        { 0, 1, 1, 1, 0 },
        { 1, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1 },
        { 0, 1, 1, 1, 0 },
        { 1, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1 },
        { 0, 1, 1, 1, 0 }
    };
    return EIGHT;
}

int main(){
    int **ptr;
    ptr = getPrint();

    return 0;
}

打印此内容的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

以下内容

#include <stdio.h>

#define N 7
#define M 5

const int ( * getPrint( void ) )[M]
{
    static const int EIGHT[N][M] = 
    {
        { 0, 1, 1, 1, 0 },
        { 1, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1 },
        { 0, 1, 1, 1, 0 },
        { 1, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1 },
        { 0, 1, 1, 1, 0 }
    };

    return EIGHT;
}

int main( void )
{
    const int ( *ptr )[M];
    int i, j;

    ptr = getPrint();

    for ( i = 0; i < N; i++ )
    {
        for ( j = 0; j < M; j++ ) printf( "%d ", ptr[i][j] );
        printf( "\n" );
    }

    return 0;
}

或者您可以使用typedef。例如

#include <stdio.h>

#define N 7
#define M 5

typedef const int ( *ArrayPtr )[M];

ArrayPtr getPrint( void )
{
    static const int EIGHT[N][M] = 
    {
        { 0, 1, 1, 1, 0 },
        { 1, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1 },
        { 0, 1, 1, 1, 0 },
        { 1, 0, 0, 0, 1 },
        { 1, 0, 0, 0, 1 },
        { 0, 1, 1, 1, 0 }
    };

    return EIGHT;
}

int main( void )
{
    ArrayPtr ptr;
    int i, j;

    ptr = getPrint();

    for ( i = 0; i < N; i++ )
    {
        for ( j = 0; j < M; j++ ) printf( "%d ", ptr[i][j] );
        printf( "\n" );
    }

    return 0;
}