1 / 9

CSci 160 Lecture 42

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.

sharonh
Download Presentation

CSci 160 Lecture 42

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSci 160Lecture 42 Martin van Bommel

  2. 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

  3. 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

  4. 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;

  5. 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”

  6. 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” };

  7. 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;

  8. 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);

  9. 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); }

More Related