简体   繁体   English

在C中打印二维数组

[英]Printing a two dimensional array in C

I want to print a two dimensional array which I get from another method, see code: 我想打印从另一个方法获得的二维数组,请参见代码:

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;
}

What would be the best method to print this? 最好的打印方法是什么?

Something as the following 如下内容

#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;
}

Or you could use a typedef. 或者您可以使用typedef。 For example 例如

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM