90 likes | 105 Views
This lecture discusses the differences between structures and arrays in programming, including their data organization, usage, and examples. It also covers how to create, initialize, and manipulate records (structures) in C, along with their usage in functions.
E N D
CSci 160Lecture 42 Martin van Bommel
Structure vs Array • Array - data is • ordered - index number • homogeneous - elements have same type • used for lists or collections • Structure - data is • unordered • heterogeneous • used for real-world objects
Structures (Records) • Example: Student • Id Number • Name • Year, Program, Major, etc. Id Name Year Program Major 20050123 John Smith 1 B.Sc. CS • Fields of structure
Records in C (Structs) • To create a record, you • Define structure type - field names and types • Declare variables of new type typedef struct { long int id; char name[NameSize]; int year; char program[PSize], major[MSize]; } student_t; student_t student;
Record Selection • Once you declare variable student_t student; can refer to it as a whole by name • However, can refer to individual fields student.name • Read it as “student dot name” • Referred to as “component selection”
Initializing Records • Can assign components values student.id = 20050123; strcpy(student.name,”John Smith”); student.year = 1; • Or can initialize during declaration student_t student = { 20050123, ”John Smith”, 1, ”B.Sc.”, ”CS” };
Simple Records • E.g. A simple point with x and y coordinates typedef struct { double x, y; } point_t; • Can do assignment with structures point1 = point2; • Equivalent to point1.x = point2.x; point1.y = point2.y;
Records in Functions • To make a point point_t CreatePoint(double x, double y) { point_t p; p.x = x; p.y = y; return (p); } origin = CreatePoint(0, 0);
Records as Arguments double Distance(point_t p1, point_t p2) { int dx, dy; dx = p1.x - p2.x; dy = p1.y - p2.y; return sqrt(dx * dx + dy * dy); }