2016-08-29 37 views
-2

我想初始化一個包含數組的數組結構的二維全局靜態數組。 以下似乎並不奏效。C - 初始化包含多個數組的結構的二維全局靜態數組

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

有什麼建議嗎?

感謝

+1

'似乎不工作。'......究竟是怎麼回事? –

+0

@SouravGhosh我認爲它不會編譯:) – niceman

+1

@niceman和哪個編譯器不生成調試消息? :) –

回答

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

你必須聲明你的2D靜態全局數組以適當的方式, 即,

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

上面的代碼工作正常。你可以檢查這個