2016-08-29 1 views
-2

Je souhaite initialiser un tableau statique global bidimensionnel de structures contenant des tableaux. Ce qui suit ne semble pas fonctionner.C - initialise un tableau statique global bidimensionnel de structures contenant plusieurs tableaux

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

Des suggestions?

Merci

+1

'ne semble pas fonctionner.' ... comment exactement? –

+0

@SouravGhosh Je pense qu'il ne compile pas :) – niceman

+1

@niceman et quel compilateur ne produit pas de message de débogage? :) –

Répondre

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

Votre déclaration de matrice doit utiliser la structure en tant que type, à savoir struct MyStuct test

Juste pour le 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

Il vous suffit de déclarer votre tableau global statique 2D de manière appropriée, soit

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

Le code ci-dessus fonctionne correctement. Vous pouvez vérifier cela