Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access pointer members in a Struct variable in C?

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.

like image 516
Raven Avatar asked Oct 26 '12 07:10

Raven


People also ask

How do you access the members of the structure 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.

How do I access pointer variables?

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.

Which operator is used to access the members of structure using pointer?

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 ( -> ).

Can a struct contain a pointer?

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.


1 Answers

Try:

myGame.victor = &myVictor;
like image 117
WhozCraig Avatar answered Sep 19 '22 05:09

WhozCraig