Les structures, contrairement aux tableaux, permettent de manipuler ensemble des données de types différents.
struct Nom_de_la_structure
{
type1 Nom1;
type2 Nom2;
type3 Nom3;
...
};
//variable statique
struct Nom_de_la_structure Nom_variable_structurée;
//pointeur
struct Nom_de_la_structure *Nom_variable_structurée;
Nom_variable_structurée.nom_variable; //variable statique
Nom_variable_structurée->nom_variable; //pointeur
ou *Nom_variable_structurée.nom_variable;
struct Personne
{
char Nom[20];
char Prenom[20];
int Age;
};
void main()
{
struct Personne P1;
printf("Nom : ");
scanf("%s",P1.Nom);
printf("Prenom : ");
scanf("%s",P1.Prenom);
printf("Age : ");
scanf("%d",&P1.Age);
printf("P1 : %s %s %d \n",P1.Nom, P1.Prenom, P1.Age);
}
Les structures de bits permettent de manipuler des champs dont la longueur est inférieure à un octet.
struct CH
{
unsigned ch0 : 4;
unsigned ch1 : 3;
unsigned ch2 : 2;
unsigned ch3 : 5;
};
La valeur indiquée derrière les 2 points correspond à une taille en bits.
Les éléments dans une union, contrairement aux structures, partagent le même emplacement mémoire. Une union occupe une taille correspondant au plus grand élément.
void main()
{
union
{
short i;
char a[2];
} U;
U.i = 263; //0000 0001 0000 0111
printf("a[0] : %x\n", U.a[0]);
printf("a[1] : %x\n", U.a[1]);
}