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 pass an array of pointers to structures to a function?ComputerScienceOne · Passing Arrays of Structures
- How can an array of structure pointers make swapping structures more efficient?ComputerScienceOne · Arrays of Structures
- How can one structure be composed of another structure?ComputerScienceOne · Declaration & Initialization
- How do you create and use an array of structures in C?ComputerScienceOne · Arrays of Structures
- How can you convert a Student structure into a string?ComputerScienceOne · To String Functions
- How do you dynamically allocate and initialize a structure?ComputerScienceOne · Selection Operators
- How can structures be dynamically allocated?ComputerScienceOne · Declaration & Initialization
- How can factory functions simplify the creation of structure instances?ComputerScienceOne · Factory Functions