Structures ANSI-C. Review: Data Structures Functions give us a way to organize programs. Data structures are needed to organize data, especially: –1.

Slides:



Advertisements
Similar presentations
Programming in C Chapter 10 Structures and Unions
Advertisements

1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
1 Structures. 2 Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members.
Structures Often we want to be able to manipulate logical entities as a whole For example, complex numbers, dates, student records, etc Each of these must.
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
1 Programming Structures COMP102 Prog. Fundamentals, Structures / Slide 2 2 Structures l A Structure is a collection of related data items, possibly.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
C Structures Basics of structures Typedef. Data Hierarchy Byte –8 bits (ASCII character ‘A’ = ) Field –Group of characters (character string “Fred”)
Structures Spring 2013Programming and Data Structure1.
Structures A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
M-1 University of Washington Computer Programming I Lecture 13 Pointer Parameters © 2000 UW CSE.
C structures and unions (Reek, Ch. 10) 1CS 3090: Safety Critical Programming in C.
User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { string name;
Heterogeneous Structures 4 Collection of values of possibly differing types 4 Name the collection; name the components 4 Example: student record harveyC.
Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because.
S-1 University of Washington Computer Programming I Lecture 18: Structures © 2000 UW CSE.
'C' Programming With Structure Records Purpose of structures Coding a structure template Defining a new data type Functions which communicate using structures.
1 Principles of Programming I Note Set #12. 2 Semester Overview Functions Character File I/O Arrays Pointers and Dynamic Memory Allocation Characters.
1 Structures. Structure (struct) Definition A Structure is a container, it can hold a bunch of things. –These things can be of any type. Structures are.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1!  And before that…  Review!  And before that…  Arrays and strings.
1 Structures UniMAP SEM I - 11/12EKT 120 Computer Programming.
COP Structures Instructor: Diego Rivera-Gutierrez I’m back baby!
Structured Programming Instructor: Prof. K. T. Tsang Lecture 11: Structure and Union 1.
Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition.
5/3/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures Lecture
Senem Kumova Metin STRUCTURES continues CHAPTER 9 in A Book in C.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
Chapter 11 Structure and Union Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
1 Structs. 2 Defining a Structure Often need to keep track of several pieces of information about a given thing. Example: Box We know its length width.
M-1 University of Washington Computer Programming I Lecture 13 Pointer Parameters © 2000 UW CSE.
11/5/2016CS150 Introduction to Computer Science 1 Announcements  Assignment 6 due on Wednesday, December 3, 2003  Final Exam on Tuesday, December 9,
Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
1 Lecture06: Complex Types 4/18/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
Multiple Items in one Data Object Arrays are a way to store more than one piece of data in a data object, provided that all the data is of the same type.
Structures 142 S -1 What is a structure? It is a collection of possibly different types Name the collection Name the components For example: a student.
STRUCTURES. C structures: aggregate, yet scalar  aggregate in that they hold multiple data items at one time  named members hold data items of various.
CSE 251 Dr. Charles B. Owen Programming in C1 structs Aggregating associated data into a single variable Box width length height Circle radius int main()
Structure A collection of values (members) struct date{ int day; char month[10]; int year; }; Declare a structure variable struct date today; struct struct_name.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
chap11 Chapter 11 Structure and Union Types.
CGS 3460 Thus Far n Whenever we declare a variable, we specified its data type. n The data type helped us identify the type of information that a variable.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
C Structures and Memory Allocation
Parallel Arrays? ANSI-C.
CS1010 Programming Methodology
Lecture 9 Structure 1. Concepts of structure Pointers of structures
הגדרת משתנים יום שלישי 27 נובמבר 2018
Array of Structures A structure holds only one record But a record
Programming in C Pointer Basics.
EECE.2160 ECE Application Programming
CS148 Introduction to Programming II
Programming in C Pointer Basics.
CS111 Computer Programming
Structures CSE 2031 Fall February 2019.
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
Structures EECS July 2019.
Chapter 10 C Structures and Unions
EECE.2160 ECE Application Programming
Chapter 11 Structure and Union Types.
Presentation transcript:

Structures ANSI-C

Review: Data Structures Functions give us a way to organize programs. Data structures are needed to organize data, especially: –1. large amounts of data –2. variable amounts of data –3. sets of data where the individual pieces are related to one another Arrays helped with points 1 and 2, but not with point 3, as arrays must contain the same type of values. – Example: the data describing one pixel: x, y,color – Example: data about one student: name, ID, gpa, etc.

structs: Heterogeneous Structures Collection of values of possibly differing types. Used to unify several values of possibly different types. Result seen as one unit. When using structs you must: –Name the collection; –name the components: called fields. Example: a student record collects under one name various pieces of information about a student: –Give name to the collection: studentRecord –Give type and name to each of the fields. Example: a date collects under one name: day, month, year.

Defining structs typedef struct { /* typedefs go at the top of the program */ char name [20] ; int id ; int hw; int exams ; double grade ; } studentRecord ; Defines a new data type called studentRecord. Does not declare (create) a variable. No storage is allocated.

Terminology A “struct” is sometimes called a “record” or “structure”. Its “components” are often called “fields” or "members".

Declaring struct variables With structs, we’re moving toward a way for programmers to define their own types. Having defined studentRecord at the top of the program: –studentRecord s1 ; –studentRecord harvey ; /*studentRecord is a type; s1 and harvey are variables. */

Selection operator:. Having declared: studentRecord s1 ; To access any of the fields: s1. fieldName Variable name. Must be of struct type field name Field selector operator

Things You Can and Can’t Do You can use = to assign whole struct variables You can have a struct as a function return type You can’t use == to directly compare struct variables; can compare fields directly You can’t directly scanf or printf structs; can read the individual fields

struct initializers …/*typedef structs go at top*/ int i1 ; int count = 0 ; char c1[5] = { ‘h’, ‘e’,’l’, ‘p’, ‘\0’}; char pet[] = “lamb” ; studentRecord harvey = {“Harvey S.”, , 87, 74, 3.1} ;

Using Components of struct Variables studentRecord s1;... scanStatus = scanf(“%d”, &s1.id) ; s1.hw = 90 ; s1.exams= 80 ; s1.grade = (double)(s1.hw + s1.exams) / 50.0 ; printf(“%d: %f”, s1.id, s1.grade) ;

Assigning Whole structs s1 = harvey ; equivalent to s1.id = harvey.id ; s1.hw = harvey.hw ; s1.exams = harvey.exams ; s1.grade= harvey.grade ; strcpy(s1.name, harvey.name) ; /* string copy – covered in slides on strings */

Why use structs? Collect together values that are treated as a unit (for compactness, readability,maintainability). –Functions can return structs –another way to have “multiple” return values. –Files and databases: collections of structs e.g., 300 (or 30,000) student records. typedef struct { int hours; int minutes ; int seconds ; } time ; typedef struct { int dollars; int cents ; } money ;

Example: /* Given 2 endpoints of a line, “return” coordinates of midpoint */ void midpoint( double x1, double y1, /* 1st endpoint */ double x2, double y2, /* 2nd endpoint */ double *midxp, double *midyp ) /* Pointers to midpoint */ { *midxp = (x1 + x2) / 2.0; *midyp = (y1 + y2) / 2.0; } double ax, ay, bx, by, mx, my;... midpoint(ax, ay, bx, by, &mx, &my);

Points as structs typedef struct { double xcoord; double ycoord; } point ;... point p1 = {0.0, 0.0}, p2 = {5.0, 10.0} ; point middle ; middle.xcoord = (p1.xcoord + p2.xcoord ) / 2.0 ; middle.ycoord = (p1.ycoord + p2.ycoord ) / 2.0 ;

Midpoint Function via structs point midpoint (point pt1, point pt2) { point mid; mid.xcoord = ( pt1.xcoord + pt2.xcoord ) / 2.0 ; mid.ycoord = ( pt1.ycoord + pt2.ycoord ) / 2.0 ; return (mid); } …/* a call */ /* point struct declaration and initialization */ point p1 = {0.0, 0.0}; point p2 = {5.0, 10.0}; point middle;... middle = midpoint (p1, p2) ; /* struct assignment */

Midpoint with references void setMidpoint (point pt1, point pt2, point *mid) { (*mid).x = ( pt1.xcoord + pt2.xcoord ) / 2.0 ; (*mid).y = ( pt1.ycoord + pt2.ycoord ) / 2.0 ; } /*. has high precedence than * */ point a = {0.0, 0.0}; point b = {5.0, 10.0}; point m; setMidpoint (a, b, &m) ; Structs behave like all non-array types whenused as parameters.

Pointer Shorthand: -> void set_midpoint (point pt1, point pt2, point *mid) { mid->x = ( pt1.xcoord + pt2.xcoord ) / 2.0 ; mid->y = ( pt1.ycoord + pt2.ycoord ) / 2.0 ; } structp - > component means (*structp).component -> is called the “indirect component selection operator”

Testing Equality of structs if (pt1 = = pt2) {... } /* Doesn’t work */ You need to specifically compare each field in the struct int pointsEqual(point pt1, point pt2) { return (pt1.xcoord = = pt2.xcoord && pt1.ycoord = = pt2.ycoord ) ; } if (pointsEqual(pt1, pt2)) {... } /* OK */

Do-it-yourself struct I/O void printPoint (point p) { printf (“(%f,%f)”, p.xcoord, p.ycoord) ; } void scanPoint (point *ptptr) { point temp ; scanf (“%lf %lf”, &temp.xcoord, &temp.ycoord) ; *ptptr = temp ; } point aPoint ; scanPoint (&aPoint) ; printPoint (aPoint) ;

Alternative scan_point void scanPoint (point *ptptr) { scanf (“%lf %lf”, & ptptr->x, & ptptr->y) ; } point aPoint ; scanPoint (&aPoint) ; printPoint (aPoint) ;

scan_point without -> void scanPoint (point *ptptr) { scanf (“%lf %lf”, &(*ptptr).x, &(*ptptr).y) ; } point aPoint ; scanPoint (&aPoint) ; print_point (aPoint) ;

Hierarchical structs typedef struct { double x; double y ; } point ; typedef struct { double width; double height ; } dimension ; typedef struct { dimension size ; point lowerLeft ; int lineColor, fillColor ; } rectangle ;

Using structs within structs point origin = { 0.0, 0.0 } ; rectangle a = { {5.0, 10.0}, {1.0, -2.0}, BLUE,CYAN}; rectangle b ; b.fillColor = BLUE ; b.lowerLeft = origin ; /* place at origin */ b.lowerLeft.y = 15.0 ; /* move up 15 */... b.size.width = 2.0 * b.size.width ; /* stretch in x */ b.size.height = 4.0 * b.size.height ; /* stretch in y */

QUIZ: Calculating Types rectangle r; rectangle * rp; r.size r.lowerLeft r.fillColor r.lowerLeft.x &r.lowerLeft.y rp -> size &rp -> lowerLeft *rp.linecolor r -> size rp -> size -> width