This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 2/17/11 1 CMSC 216 Introduction to Computer Systems Lecture 6 Strings, cont. & Structures and Unions & Input/Output Jan Plane & Pete Keleher {jplane, [email protected] Administrivia • Read Reek, Chapter 10: Structures and Unions 2 2/17/11 2 S TRUCTURES AND U NIONS Chapter 10, Reek 3 Structures and functions • Structure arguments are passed by value • We can return structures from functions Section add_students(Section sec, int students_to_add) { Section new_section = sec; new_section.num_students += students_to_add; return new_section; } Section s = { 0101, 10, 1400 }, t; ... t = add_students(s, 26); 4 2/17/11 3 Aside: parameters are variables, too! • Because arguments are passed and returned by value, you can use the parameters as variables: Section add_students(Section sec, int students_to_add) { sec.num_students += students_to_add; return sec; } Section s = { 0101, 10, 1400 }, t; ... t = add_students(s, 26); 5 Unions • Look much like structures • But all fields share the same memory space, so are only as large as largest field • Only one field valid at a time typedef union { int i; double d; } Number; ... Number a, b; a.i = 2; b.d = 3.14159; printf(“%d\n”, b.i); 6 blue bytes are used when accessed as an int, red bytes used when accessed as a double 2/17/11 3 Aside: parameters are variables, too! • Because arguments are passed and returned by value, you can use the parameters as variables: Section add_students(Section sec, int students_to_add) { sec.num_students += students_to_add; return sec; } Section s = { 0101, 10, 1400 }, t; ... t = add_students(s, 26); 5 Unions • Look much like structures • But all fields share the same memory space, so are only as large as largest field • Only one field valid at a time typedef union { int i; double d; } Number;...
View
Full
Document
This note was uploaded on 11/16/2011 for the course CMSC 216 taught by Professor Plane during the Spring '11 term at Maryland.
 Spring '11
 Plane

Click to edit the document details