Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCE 206 Lab Structured Programming in C

Similar presentations


Presentation on theme: "CSCE 206 Lab Structured Programming in C"— Presentation transcript:

1 CSCE 206 Lab Structured Programming in C
Spring 2019 Lecture 8

2 Structs A struct is a user-defined data type
Used to group one or more variables into the same type struct student { char name[30]; int uin; int phone_num; int gpa; }; struct keyword structure tag Semicolon, do not forget to put it!

3 Structs: create a type typedef struct { char name[30]; int uin; int phone_num; float gpa; } Student; Use uppercase in types! (not for variables)

4 Use a type struct void main() { Student s1, s2; // declaration of two students with a Student type s1.gpa = 3.8; // set gpa value for the first student s2.gpa = 3.3; // set gpa for the second }

5 Use a type struct in functions
Student highestGPA(Student s1, Student s2) { if (s1.gpa > s2.gpa) return s1; else return s2; } void main() { Student s1, s2; // declaration of two students with a Student type s1.gpa = 3.8; // set gpa value for the first student s2.gpa = 3.3; // set gpa for the second Student best = highestGPA(s1, s2);

6 Use a type struct inside the struct
typedef struct Node { char name[30]; int uin; int phone_num; float gpa; struct Node *next; // you can only use the same type if declared in first line } Node;

7 Use a type struct with a pointer
void main() { Student s1; Student *pS1 = &s1; //pointer to student pS1->gpa = 3.8; // when using a pointer use -> instead of ‘.’ }

8 Arrays of structs void main() { Student class[10]; class[0].gpa = 3.8; // modify GPA of first student of the class }

9 Structs that contain structs
typedef struct { float test1; float test2; } Grades; int uin; Grades grades; } Student; void main() { Student class[10]; class[0].grades.test1 = 83.2; // modify first grade of first student of the class }

10 Accessing structs Student s; Student *ptr = &s; ptr->grades.test1 = 84.1; // through a pointer s.grades.test2 = 96.2; // through the student (*ptr).uin = ; // beware of the parenthesis!


Download ppt "CSCE 206 Lab Structured Programming in C"

Similar presentations


Ads by Google