C initialisation du tableau de tableaux

J’ai ce problème. J’ai besoin d’un tableau de tableaux flottants à stocker avant d’exécuter certaines fonctions. Comment puis-je accomplir cela, étant donné que je ne peux pas initialiser un tableau sans être constant? Devrais-je créer une fonction qui va créer ce tableau avec malloc, puis revenir et atsortingbuer à un pointeur?

typedef struct { float RGBA[4]; } graphColors; 

J’ai besoin d’un tableau de grapColors. Je suis désolé pour mon manque de connaissances, je suis un programmeur Java et je dois travailler avec C maintenant.

MODIFIER:

 graphColors *initializeGraphColors(){ graphColors *gp; int i; float HI = 1.0f; float LO = 0.0f; float temp[] = {1.0f, 1.0f, 1.0f, 0.0f}; gp = (graphColors *) malloc(nrOfLines * sizeof(graphColors)); for(i = 0;i < nrOfLines; i++){ gp[i].RGBA[0] = LO + (float)rand()/((float)RAND_MAX/(HI-LO)); gp[i].RGBA[1] = LO + (float)rand()/((float)RAND_MAX/(HI-LO)); gp[i].RGBA[2] = LO + (float)rand()/((float)RAND_MAX/(HI-LO)); gp[i].RGBA[3] = 0.0f; } return gp; } 

Puis dans ma classe:

 graphColors *gc; gc = initializeGraphColors(); 

Obtenir cette erreur:

 error C2040: 'gc' : 'graphColors *' differs in levels of indirection from 'graphColors' 

Si les valeurs que vous devez stocker dans le tableau ne sont pas connues au moment de la compilation, vous aurez besoin d’une fonction bien que vous n’ayez à allouer un tableau via malloc() si la taille du tableau est inconnue au moment de la compilation.

Donc … si la taille et le contenu sont connus au moment de la compilation, vous pouvez le faire …

 #define NUM_ELEMENTS 2 typedef struct { float RGBA[4]; } graphColors; graphColors array[NUM_ELEMENTS] = { { 1.0, 0.4, 0.5, 0.6 }, { 0.8, 0.2, 0.0, 1.0 } } 

Si la taille est connue, mais pas les valeurs, vous pouvez le faire …

 #define NUM_ELEMENTS 2 typedef struct { float RGBA[4]; } graphColors; graphColors array[NUM_ELEMENTS]; void InitGraph() { for( int i = 0; i < NUM_ELEMENTS; i++ ) { for( int j = 0; j < 4; j++ ) { array[i][j] = GetValue( i, j ); } } } 

Si vous ne connaissez pas la taille ou le contenu avant l'exécution, vous pouvez l'aborder de cette façon ...

 typedef struct { float RGBA[4]; } graphColors; graphColors* array = NULL; void InitGraph( int num_elements ) { array = malloc( sizeof( graphColors ) * num_elements ); if( !array ) { printf( "error\n" ); exit( -1 ); } for( int i = 0; i < num_elements; i++ ) { for( int j = 0; j < 4; j++ ) { array[i][j] = GetValue( i, j ); } } }