【问题标题】:C – initialize a two dimensional global static array of structs that contain more than one arrayC – 初始化包含多个数组的二维全局静态结构数组
【发布时间】:2017-01-05 06:40:23
【问题描述】:

我想初始化一个二维全局静态结构数组,其中包含数组。 以下似乎不起作用。

struct MyStuct{
    int a;
    int b;
    int c[2];
    int d[2];
};
STATIC MyStuct[2][3] = {
{{1,1,{1,1},{1,1}},
{2,2,{2,2},{2,2}},
{3,3,{3,3},{3,3}}},
{{7,7,{7,7},{7,7}},
{8,8,{8,8},{8,8}},
{9,9,{9,9},{9,9}}}
};

有什么建议吗?

谢谢

【问题讨论】:

  • doesn’t seems to work....到底怎么样?
  • @SouravGhosh 我认为它无法编译 :)
  • @niceman 哪个编译器不会产生调试消息? :)

标签: c arrays struct initialization ini


【解决方案1】:
struct MyStuct{
    int a;
    int b;
    int c[2];
    int d[2];
};

static struct MyStuct test [2][3] =
{
//            |     COL 0     |  |     COL 1     |  |    COL 2      |
/* ROW 0 */ { {1,1,{1,1},{1,1}}, {2,2,{2,2},{2,2}}, {3,3,{3,3},{3,3}} },
/* ROW 1 */ { {7,7,{7,7},{7,7}}, {8,8,{8,8},{8,8}}, {9,9,{9,9},{9,9}} }
};

您的矩阵声明必须使用结构作为类型,即struct MyStuct test

仅供测试:

#include <stdio.h>

int main (void)
{
    struct MyStuct{
        int a;
        int b;
        int c[2];
        int d[2];
    };

    struct MyStuct test [2][3] =
    {
    //            |     COL 0      |       COL 1       |      COL 2        |
    /* ROW 0 */ { {1,1,{1,1},{1,1}}, {2,2,{2,2},{2,2}}, {3,3,{3,3},{3,3}} },
    /* ROW 1 */ { {7,7,{7,7},{7,7}}, {8,8,{8,8},{8,8}}, {9,9,{9,9},{9,9}} }
    };

    for (size_t i=0; i< 2; i++)
    {
        for (size_t j=0; j<3; j++)
        {
            printf("test[%zu][%zu].a = %d\n", i, j, test[i][j].a);
            printf("test[%zu][%zu].b = %d\n", i, j, test[i][j].b);

            for (size_t z=0; z<sizeof(test[i][j].c)/sizeof(test[i][j].c[0]); z++)
            {
                printf("test[%zu][%zu].c[%zu] = %d\n", i, j, z, test[i][j].c[z]);
            }

            for (size_t z=0; z<sizeof(test[i][j].c)/sizeof(test[i][j].c[0]); z++)
            {
                printf("test[%zu][%zu].d[%zu] = %d\n", i, j, z, test[i][j].c[z]);
            }

            printf("\n");
        }
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    你只需要以正确的方式声明你的二维静态全局数组, 即,

    struct MyStuct{
        int a;
        int b;
        int c[2];
        int d[2];
    };
    static MyStuct arrayName[2][3] = {
        { { 1, 1, { 1 ,1 }, { 1, 1 } },
        { 2, 2, { 2, 2 }, { 2, 2 } },
        { 3, 3, { 3, 3 }, { 3, 3 } } },
        { { 7, 7, { 7, 7 }, { 7, 7 } },
        { 8, 8, { 8, 8 }, { 8, 8 } },
        { 9, 9, { 9, 9 }, { 9, 9 } } }
    };
    

    上面的代码工作正常。你可以看看这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-06
      • 2022-12-03
      • 1970-01-01
      • 2011-04-14
      • 2023-04-08
      • 2020-05-28
      • 2011-02-08
      • 2014-10-31
      相关资源
      最近更新 更多