Déclarer 2 structures contenant chacune un membre de l'autre structure
Le code suivant ne compile pas car lors de la définition de 'STRUCT_A', 'STRUCT_B' n'est pas défini:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Structure A
typedef struct {
int valeur_a;
STRUCT_B *ptr_struct_b;
} STRUCT_A;
// Structure B
typedef struct {
int valeur_b;
STRUCT_A *ptr_struct_a;
} STRUCT_B;
int main(void)
{
int val;
STRUCT_A a;
STRUCT_B b;
a.ptr_struct_b = &b;
b.valeur_b = 10;
val = a.ptr_struct_b->valeur_b;
printf("Val: %d\n", val);
return(0);
} |
Une solution est de passer par un 'void*', mais cela ne me semble pas très propre:
Existe t-il un moyen de déclarer autrement ces structures pour ne pas avoir à indiquer le 'void *' ?
En effet, le code suivant compile bien mais est propice aux erreurs:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Structure A
typedef struct {
int valeur_a;
void *ptr_struct_b;
} STRUCT_A;
// Structure B
typedef struct {
int valeur_b;
STRUCT_A *ptr_struct_a;
} STRUCT_B;
int main(void)
{
int val;
STRUCT_A a;
STRUCT_B b;
a.ptr_struct_b = &b;
b.valeur_b = 10;
// val = a.ptr_struct_b->valeur_b;
STRUCT_A *ptr_b;
ptr_b = a.ptr_struct_b;
val = ptr_b->valeur_b;
printf("Val: %d\n", val);
return(0);
} |
Val : 10 (OK)
Par exemple, le code suivant est dans les choux:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Structure A
typedef struct {
int valeur_a;
void *ptr_struct_b;
} STRUCT_A;
// Structure B
typedef struct {
int bug;
int valeur_b;
STRUCT_A *ptr_struct_a;
} STRUCT_B;
int main(void)
{
int val;
STRUCT_A a;
STRUCT_B b;
a.ptr_struct_b = &b;
b.valeur_b = 10;
b.bug = 99;
a.valeur_a = 15;
//val = a.ptr_struct_b->valeur_b;
STRUCT_A *ptr_b;
ptr_b = a.ptr_struct_b;
val = ptr_b->valeur_a;
printf("Val: %d\n", val);
return(0);
} |
Val : 99 !!!
Si le void* n'était pas présent, on aurait une erreur de compilation sur 'ptr_b = a.ptr_struct_b;' et on se rendrait compte que ptr_b est mal déclaré.
Ma question peut paraitre idiote mais sur un soft avec plein de structures et de pointeurs elle prend toute son importance.