Bifalgorithm post · Computer science one · Selection Operators

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

How do you access members through a pointer to a structure? (Computer science one · Selection Operators) — "When we have a pointer to a structure, we cannot di…

Ideas in this flowchart

  • Zugriff auf Strukturmitglieder über einen Zeiger in C
  • Der Punktoperator kann nicht direkt auf einen Strukturzeiger angewendet werden.
  • Der Zeiger muss dereferenziert werden, bevor der Punktoperator verwendet wird.
  • Wegen der höheren Priorität des Punktoperators sind Klammern erforderlich: (*s).id.
  • Der Pfeiloperator -> kombiniert Dereferenzierung und Auswahl eines Strukturmitglieds.
  • Nach der Speicherreservierung können Mitglieder wie s->id und s->gpa gesetzt werden.
  • Zeichenkettenmitglieder werden separat reserviert, kopiert und anschließend über den Pfeiloperator ausgegeben.
  • Ein eingebettetes dateOfBirth-Objekt wird mit dem Punktoperator erreicht: s->dateOfBirth.year.
  • Ist dateOfBirth dagegen ein Zeiger, werden zwei Pfeiloperatoren verwendet: s->dateOfBirth->year.
Feed/

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

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.