100 likes | 328 Views
CSCE 206 Lab Structured Programming in C. Spring 2019 Lecture 8. Structs. struct keyword. structure tag. Semicolon, do not forget to put it!. 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 ;
E N D
CSCE 206 Lab Structured Programming in C Spring 2019 Lecture 8
Structs struct keyword structure tag Semicolon, do not forget to put it! • A struct is a user-defined data type • Used to group one or more variables into the same type struct student { char name[30]; intuin; intphone_num; intgpa; };
Structs: create a type typedef struct { char name[30]; intuin; intphone_num; float gpa; } Student; Use uppercase in types! (not for variables)
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 }
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); }
Use a type struct inside the struct typedef struct Node { char name[30]; intuin; intphone_num; float gpa; struct Node *next; // you can only use the same type if declared in first line } Node;
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 ‘.’ }
Arrays of structs void main() { Student class[10]; class[0].gpa = 3.8; // modify GPA of first student of the class }
Structs that contain structs typedef struct { float test1; float test2; } Grades; typedef struct { intuin; Grades grades; } Student; void main() { Student class[10]; class[0].grades.test1 = 83.2; // modify first grade of first student of the class }
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 = 123456789; // beware of the parenthesis!