I have read somewhere that if you create user defined data type like structure, the compiler will "give" the address of that structure (It the first element) to the name of the structure. struct person p1, p1 will also hold it's address.
If this is true, why did this code not work ?
main(void) {
typedef struct personne{
char nom [20] ;
char prenom [15] ;
int age ;
char tel[12] ;
} personne ;
personne p;
p->age=10;
printf("%d",p->age);
}
ERROR MESSAGE: base operand of '->' has non-pointer type 'personne {aka main()::personne}'
In general, all variables in your program occupy some memory space. The space is allocated by the compiler at a known address of the virtual memory.
So, personne p; asks compiler to allocate space in memory for variable p sufficient to keep the data for all fields of the struct. The compiler knows the address of the variable p. You can always ask the program to give you that address as &p. The address is essensially the pointer to the struct.
The variables in 'c' can contain data (as your p) or a a pointer. A pointer variable keeps an address which is associated with another variable. A pointer varialbe also occupies space in memory and you can get its address as well.
But in your case you can use something like the following:
personne pstruct; // delcare your struct
personne *p = &pstruct; // delare a pointer to the struct and intialize it with the address of 'pstruct'
p->age=10;
printf("%d",p->age);
This should work now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With