User Tools

Site Tools


Exercise - Accessing struct fields using pointers


  • Better understand call by reference when passing parameters
  • Use pointer variables and the operator to access fields in a struct
  • Feel free to refer to Dive Into Systems Section 2.7 for, uh, “pointers”


In this section you'll complete a program that creates and initializes two struct variables, one a regular struct variable and the other dynamically allocated through a pointer. As written the code initializes the first struct but the second is left for you to do. Also, there is a print_student function that takes a pointer to struct studentT as an argument (is this call by value or call by reference?) but this function is incomplete.

  1. Download the program ptr-struct.c from the webserver
  2. Give it a quick read to get the idea
  3. The places to add code are marked by a comment saying …add code here… and I recommend completing the initialization of the second struct (using a pointer), in the main function, first. Fill in any values you like for each field of the struct.
  4. Now complete code for the print_student function.
  5. Compile and test. When you have it working, demonstrate to the instructor

As always, if you run out of time or are working remotely, send me an e-mail containing screenshots of the working programs by the end of the day for full credit.

cs270/ptr2struct.txt · Last modified: 2021/09/20 17:16 by scarl