{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

79_pdfsam_cs2022

79_pdfsam_cs2022 - Structures Structures aggregate...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Structures Structures aggregate variables of different types Like classes in Java, but they can only store data Defined with the keyword struct // define new structure struct Student { int id, year; char grade; }; int main() { struct Student s; s.id = 10001; s.year = 2010; s.grade = ‘B’; printf(“%d %d %c\n”, s.id, s.year, s.grade); } (int) id (int) year (char) grade struct student 0 4 8 struct student requires approximately 9 bytes
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Structure syntax To define a structure To declare a variable of the new structure type The struct keyword is required in both places struct structure_name { /* list of variable declarations */ }; int main() { struct structure_name variable_name; /* code */ }
Background image of page 2
Structures and typedef To avoid the struct keyword, use a typedef create alias for struct Student_struct called Student // define new structure struct Student_struct { int id, year; char grade; }; typedef struct Student_struct Student; int main() { Student s; s.id = 10001; s.year = 2010; s.grade = ‘B’; printf(“%d %d %c\n”, s.id, s.year, s.grade); }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Another example: 2-D points // define new structure typedef struct { double x, y;
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 6
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}