ESC101: Introduction to Computing Structures. Motivation Till now, we have used data types int, float, char, arrays (1D, 2D,...) and pointers. What if.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

EASTERN MEDITERRANEAN UNIVERSITY EENG212 ALGORITHMS & DATA STRUCTURES Structures in C.
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Programming in C Chapter 10 Structures and Unions
C Language.
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.
1 Structures. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc) and other.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming Languages and Paradigms The C Programming Language.
Structures Spring 2013Programming and Data Structure1.
Structures in C.
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, Unions, and Typedefs CIS 1057 Fall Structures, Unions, and Typedefs CIS 1057 Computer Programming in C Fall 2013 (Many slides based on/borrowed.
Kernighan/Ritchie: Kelley/Pohl:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
Structures, Unions, and Typedefs CS-2301 D-term Structures, Unions, and Typedefs CS-2301 System Programming D-term 2009 (Slides include materials.
C and Data Structures Baojian Hua
Introduction to C Programming CE Lecture 10 Data Structures typedef and struct.
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Structures and UnionsCS-2301 B-term Structures and Unions CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
Structures, Unions, and Typedefs CS-2303, C-Term Structures, Unions, and Typedefs CS-2303 System Programming Concepts (Slides include materials from.
LECTURE 4: INFORMATION REPRESENTATION (PART II) COMP26120: ALGORITHMS AND IMPERATIVE PROGRAMMING.
8. Structures, File I/O, Recursion 18 th October IIT Kanpur 1C Course, Programming club, Fall 2008.
Working with Structures. Structure Declaration ä Creates a user-defined data type. ä Gives the compiler a “head’s up” as to what the structure contains.
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.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Review C Language Features –control flow –C operators –program structure –data types –I/O and files Problem Solving Abilities.
Learners Support Publications Classes and Objects.
Week 9 - Monday.  What did we talk about last time?  Time  GDB.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
ECE 103 Engineering Programming Chapter 49 Structures Unions, Part 1 Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE.
CS 261 – Data Structures Introduction to C Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 13: Data structures in C.
Welcome to Concepts of Pointers. Prepared by:- Sumit Kumar PGT(Computer Science) Kv,Samba.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CPS120: Introduction to Computer Science Lecture 15A Structures.
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
CPS120: Introduction to Computer Science Data Structures.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Introduction to Computers and Programming Class 24 Structures (structs) Professor Avi Rosenfeld.
ENEE150 – 0102 ANDREW GOFFIN More With Pointers. Importance of Pointers Dynamic Memory (relevant with malloc) Passing By Reference Pointer Arithmetic.
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.
1 Structures & Unions. 2 User-Defined Types C provides facilities to define one’s own types. These may be a composite of basic types ( int, double, etc)
C Structures and Memory Allocation
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
C Basics.
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Derived types.
Lecture 18 Arrays and Pointer Arithmetic
Classes and Objects.
Structures, Unions, and Typedefs
CS111 Computer Programming
Structures CSE 2031 Fall February 2019.
Java Programming Language
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
Programming Languages and Paradigms
Structures EECS July 2019.
C Structures and Memory Allocation
Week 9 - Monday CS222.
Presentation transcript:

ESC101: Introduction to Computing Structures

Motivation Till now, we have used data types int, float, char, arrays (1D, 2D,...) and pointers. What if we want to define our own data types based on these? A geometry package – we want to define a point as having an x coordinate, and a y coordinate. Student data – Name and Roll Number  array of size 2?  two variables:  int point_x, point_y;  char *name; int roll_num;

Motivation A geometry package – we want to define a point as having an x coordinate, and a y coordinate. Student data – Name and Roll Number  array of size 2? (Can not mix TYPES)  two variables:  int point_x, point_y;  char *name; int roll_num;  There is no way to indicate that they are part of the same point!  requires a disciplined use of variable names Is there any better way ?

Motivation: Practical Example Write a program to manage customer accounts for a large bank. Customer information as well as account information, for e.g.: Account Number Account Type Customer Name Customer Address Signature scan int int (enum – not covered) char*/char[] bitmap image (2-D array of bits)

Structures This defines a structure called point containing two integer variables (fields), called x and y. struct point { int x; int y; }; struct point pt; struct point pt defines a variable pt to be of type struct point. x y pt memory depiction of pt A structure is a collection of variables with a common name. The variables can be of different types (including arrays, pointers or structures themselves!). Structure variables are called fields.

Structures The x field of pt is accessed as pt.x. Field pt.x is an int and can be used as any other int. Similarly the y field of pt is accessed as pt.y pt.x = 0; pt.y = 1; struct point { int x; int y; }; struct point pt; memory depiction of pt x y pt 1 0

struct point { int x; int y; } struct point pt1,pt2; struct point pts[6]; struct point is a type. It can be used just like int, char etc.. We can define array of struct point also. x y pts x y x y x y x y x y pts[0]pts[1]pts[2]pts[3]pts[4]pts[5] int i; for (i=0; i < 6; i=i+1) { pts[i].x = i; pts[i].y = i; } Read pts[i].x as (pts[i]).x The. and [] operators have same precedence. Associativity: left-right. For now, define structs in the beginning of the file, after #include. Structures

Announcements Major Quiz 2 -> Tomorrow (31 st March) Thursday/Friday : Holiday Makeup lab? Lab Exam on April 12 th Details – Early next week

Structures struct point { int x; int y; }; struct point pts[6]; int i; for (i=0; i < 6; i=i+1) { pts[i].x = i; pts[i].y = i; } x y pts x y x y x y x y x y pts[0]pts[1]pts[2]pts[3]pts[4]pts[5] State of memory after the code executes.

Reading structures (scanf ?) struct point { int x; int y; }; int main() { int x, y; struct point pt; scanf(“%d%d”, &(pt.x),&(pt.y)); return 0; } 1. You can not read a structure directly using scanf! 2. Read individual fields returns using scanf. 3. A better way is to define our own functions to read structures  to avoid cluttering the code!

Functions returning structures struct point { int x; int y; }; struct point make_point (int x, int y) { struct point temp; temp.x = x; temp.y = y; return temp; } int main() { int x, y; struct point pt; scanf(“%d%d”, &x,&y); pt = make_point(x,y); return 0; } 1. make_point(x,y) creates a struct point given coordinates (x,y). 2. Note: make_point(x,y) returns struct point. 3. Functions can return structures just like int, char, int *, etc.. 4. We can also pass struct parameters. struct are passed by copying the values. Given int coordinates x,y, make_point(x,y) creates and returns a struct point with these coordinates.

Functions with structures as parameters # include struct point { int x; int y; }; double norm2( struct point p) { return sqrt ( p.x*p.x + p.y*p.y); } int main() { int x, y; struct point pt; scanf(“%d%d”, &x,&y); pt = make_point(x,y); printf(“distance from origin is %f ”, norm2(pt) ); return 0; } The norm2 or Euclidean norm of point (x,y) is norm2(struct point p) returns Euclidean norm of point p.

Structures inside structures struct point { int x; int y; }; 1. Recall, a structure definition defines a type. 2. Once a type is defined, it can be used in the definition of new types. 3. struct point is used to define struct rect. Each struct rect has two instances of struct point. struct rect { struct point leftbot; struct point righttop; }; struct rect r; x y x y leftbotrighttop r r is a variable of type struct rect. It has two struct point structures as fields. So how do we refer to the x of leftbot point structure of r?

struct point { int x; int y; }; struct rect { struct point leftbot; struct point righttop; }; int main() { struct rect r; r.leftbot.x = 0; r.leftbot.y = 0; r.righttop.x = 1; r.righttop.y = 1; return 0; } x y x yleftbotrighttop r r.leftbot.y r.leftbot.x r.righttop.y r.righttop.x Addressing nested fields unambiguously

Initializing structures struct point { int x; int y; }; 1. Initializing structures is very similar to initializing arrays. 2. Enclose the values of all the fields in braces. 3. Values of different fields are separated by commas. struct rect { struct point leftbot; struct point righttop; }; struct point p = {0,0}; struct point q = {1,1}; struct rect r = {{0,0}, {1,1}}; p (0,0) (1,1) q r

Assigning structure variables x y x y leftbotrighttop 1. We can assign a structure variable to another structure variable 2. The statement s=r; does this r struct rect r,s; r.leftbot.x = 0; r.leftbot.y = 0; r.righttop.x = 1; r.righttop.y = 1; s=r; x x y x y leftbotrighttop s Before the assignment

Assigning structure variables x y x y leftbotrighttop 1. We can assign a structure variable to another structure variable 2. The statement s=r; does this r struct rect r,s; r.leftbot.x = 0; r.leftbot.y = 0; r.righttop.x = 1; r.righttop.y = 1; s=r; x After the assignment s x y x y leftbotrighttop x

Passing structures..? struct rect { struct point leftbot; struct point righttop; }; int area(struct rect r) { return (r.righttop.x – r.leftbot.x) * (r.righttop.y – r.leftbot.y); } void fun() { struct rect r1 ={{0,0}, {1,1}}; area(r1); } x y x y leftbotrighttop r Usually NO. E.g., to pass struct rect as parameter, 4 integers are copied. This is expensive. But is it efficient to pass structures or to return structures? We can pass structures as parameters, and return structures from functions, like the basic types int, char, double etc.. Same for returning structures So what should be done to pass structures to functions?

Passing structures..? struct rect { struct point leftbot; struct point righttop;}; int area(struct rect *pr) { return ((*pr).righttop.x – (*pr).leftbot.x) * ((*pr).righttop.y – (*pr).leftbot.y); } void fun() { struct rect r ={{0,0}, {1,1}}; area (&r); } x y x y leftbotrighttop r Now only one pointer is passed instead of a large struct. area() uses a pointer to struct rect pr as a parameter, instead of struct rect itself. Instead of passing structures, pass pointers to structures. Same for returning structures

Structure Pointers struct point { int x; int y;}; struct rect { struct point leftbot; struct point righttop; }; struct rect *pr; 1. *pr is pointer to struct rect. 2. To access a field of the struct pointed to by struct rect, use (*pr).leftbot (*pr).righttop 3. Bracketing (*pr) is essential here. * has lower precedence than. 4. To access the x field of leftbot, use (*pr).leftbot.x pr x y x y leftbotrighttop (*pr).leftbot.y(*pr).righttop.y (*pr).righttop.x Addressing fields via the structure’s pointer (*pr).leftbot.x

Structure Pointers struct point { int x; int y;}; struct rect { struct point leftbot; struct point righttop; }; struct rect *pr; 1. Pointers to structures are used so frequently that a shorthand notation (->) is provided. 2. To access a field of the struct pointed to by struct rect, use pr->leftbot 3. -> is one operator. To access the x field of leftbot, use pr->leftbot.x 3. -> and. have same precedence and are left-associative. Equivalent to (pr->leftbot).x pr x y x y leftbotrighttop pr->leftbot.ypr->righttop.y Addressing fields via the structure’s pointer (shorthand) pr->leftbot.xpr->righttop.x pr->leftbot is equivalent to (*pr).leftbot

Passing struct to functions When a struct is passed directly, it is passed by copying its contents Any changes made inside the called function are lost on return This is same as that for simple variables When a struct is passed using pointer, Change made to the contents using pointer dereference are visible outside the called function

Dynamic Allocation of struct Similar to other data types sizeof(…) works for struct-s too struct point* pts; int i; pts = (struct point*) malloc(6 * sizeof(struct point)); for (i = 0; i < 6; i++) pts[i] = make_point(i, i); x y pts x y x y x y x y x y pts[0]pts[1]pts[2]pts[3]pts[4]pts[5]

(Re)defining a Type - typedef When using a structure data type, it gets a bit cumbersome to write struct followed by the structure name every time. Alternatively, we can use the typedef command to set an alias (or shortcut). struct point { int x; int y; }; typedef struct point Point; struct rect { Point leftbot; Point righttop; }; typedef struct point { int x; int y; } Point; We can merge struct definition and typedef:

More on typedef typedef may be used to rename any type Convenience in naming Clarifies purpose of the type Cleaner, more readable code Portability across platforms Syntax typedef Existing-Type NewName; Existing type is a base type or compound type NewName must be an identifier (same rules as variable/function name)

More on typedef typedef char* String; // String: a new name to char pointer typedef int size_t; // Improved // Readability typedef struct point* PointPtr; typedef long long int64; // Portability

Practical Example: Revisited Customer information Struct cust_info { int Account_Number; int Account_Type; char *Customer_Name; char* Customer_Address; bitmap Signature_scan; // user defined type bitmap } Customer can have more than 1 accounts Want to keep multiple accounts for a customer together for easy access

Customer Information : Updated “Link” all the customer accounts together using a “chain-of-pointers” Struct cust_info { int Account_Number; int Account_Type; char *Customer_Name; char* Customer_Address; bitmap Signature_scan; // user defined type bitmap struct cust_info* next_account; } Why not: struct cust_info next_account;

name next custs ABACCA custs[0]custs[1] custs[2] custs[3] custs[4] custs[5] NULL cust[i].next, cust[i].next->next, cust[i].next->next->next etc., when not NULL, point to the “other” records of the same customer