I'm not new to C but I just found out a problem which I have to deal with. How do I access the member of a struct that is a pointer to another struct?
ex.
typdef struct {
int points;
} tribute;
typedef struct {
int year;
tribute *victor;
} game;
int main(){
tribute myVictor;
myVictor.points = 10;
game myGame;
myGame.year = 1994; // Runs fine
myGame.victor = myVictor; // I want to point the victor member of the game struct to
//myVictor object... But it gives me an error
}
How could I correct this? I know that I should've made the myGame variable as a pointer.. but I'm asking if I can do this in a normal struct variable.
Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures.
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
You can access a structure member using pointers, of type structure, in the following ways; 1) Using the arrow operator: If the members of the structure are public then you can directly access them using the arrow operator ( -> ).
Structures can also contain pointers, either to basic types or to structs of the same or different types. struct Employee { char *name; struct Date * hiringDate; }; This can cause potential problems if a struct containing a pointer is copied using the assignment operator, or passed by value to a function.
Try:
myGame.victor = &myVictor;
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