Vous devez comprendre comment fonctionne un pointeur alloué :
- Supposons que vous ayez alloué de la mémoire pour trois structs
Ptr = malloc(3*sizeof(EXE))
.
- Ensuite, lorsque vous ajoutez 1 à Ptr, il arrive à la structure suivante. Vous avez un bloc de mémoire divisé par 3 (3 blocs de mémoire plus petits pour chaque structure).
- Donc, il faut accéder aux éléments de la première structure et ensuite déplacer le pointeur vers la suivante.
Vous pouvez comprendre ici comment cela fonctionne :
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *s;
char d;
} EXE;
int main()
{
int i;
EXE *Ptr;
Ptr = malloc(3*sizeof(EXE)); // dymnamically allocating the
// memory for three structures
Ptr->s = "ABC";
Ptr->d = 'a';
//2nd
Ptr++; // moving to the 2nd structure
Ptr->s = "DEF";
Ptr->d = 'd';
//3rd
Ptr++; // moving to the 3rd structure
Ptr->s = "XYZ";
Ptr->d = 'x';
//reset the pointer `Ptr`
Ptr -= 2; // going to the 1st structure
//printing the 1st, the 2nd and the 3rd structs
for (i = 0; i < 3; i++) {
printf("%s\n", Ptr->s);
printf("%c\n\n", Ptr->d);
Ptr++;
}
return 0;
}
Avis : - Si vous avez une variable d'une structure, utilisez .
opérateur d'accès aux éléments. - Si vous avez un pointeur sur une structure, utilisez ->
opérateur pour accéder aux éléments.
#include <stdio.h>
#include <stdlib.h>
struct EXE {
int a;
};
int main(){
struct EXE variable;
struct EXE *pointer;
pointer = malloc(sizeof(struct EXE)); // allocating mamory dynamically
// and making pointer to point to this
// dynamically allocated block of memory
// like here
variable.a = 100;
pointer->a = 100;
printf("%d\n%d\n", variable.a, pointer->a);
return 0;
}