Concept

How do you access members through a pointer to a structure?

ComputerScienceOne / Selection Operators

"When we have a pointer to a structure, we cannot directly use the dot operator. Instead, we have to change the pointer into a “normal” structure by dereferencing it, then we can use the dot operator. However, the dot operator has a higher order of precedence than the dereferencing operator, thus parentheses are required:\n\nStudent *s = ...;\n\n(*s).id = 87654321;\n\nThis can be a bit unwieldy, so C provides a convenience operator, the indirect component selector operator, or more commonly, the arrow operator that allows us to select a member variable with a single operator that resembles a right-pointing arrow.\n\nStudent *s = (Student *) malloc(sizeof(Student));\n\n//set values:\n\ns->id = 87654321;\n\ns->gpa = 3.9;\n\n//initialize the string variables:\n\ns->firstName = (char *) malloc(sizeof(char) * 6);\n\nstrcpy(s->firstName, \"Grace\");\n\ns->lastName = (char *) malloc(sizeof(char) * 7);\n\nstrcpy(s->lastName, \"Hopper\");\n\n//access values:\n\nprintf(\"Name: %s, %s\n\n\", s->lastName, s->firstName);\n\nprintf(\"GPA: %.2f\n\n\", s->gpa);\n\ns->dateOfBirth.year = 2525;\n\nNote the last line: the dateOfBirth member variable was another structure, but not a pointer to a structure, so we use the dot operator to access the year member variable. Alternatively, we could have defined dateOfBirth to be a pointer, Date *dateOfBirth; in the Student structure. If we had, then to access the year member variable using two arrow operators, s->dateOfBirth->year."

Related Ideas

How do you access members through a pointer to a structure? | ComputerScienceOne | Bifalgorithm | Bifalgorithm