CNG 140 C Programming (Lecture set 10) Spring 2006-2007 Chapter 12 Structures.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Pointers.
C Language.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Structures Spring 2013Programming and Data Structure1.
Structures in C.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Lecture 2 Introduction to C Programming
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
Engineering Computing I Chapter 6 Structures. Sgtructures  A structure is a collection of one or more variables, possibly of different types, grouped.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
A First Book of ANSI C Fourth Edition
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 8 Arrays and Strings
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
計算機程式語言 Lecture 13-1 國立臺灣大學生物機電系 13 Structures.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Chapter 10 Introduction to Classes
Structures Combining data types into a logical groupings.
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Engineering Problem Solving with C Fundamental Concepts Chapter 7 Structures.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
Arrays and Pointers1 Arrays of Arrays: We can have arrays of any type, even arrays whose elements are themselves arrays. With two bracket pairs, we obtain.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 7: Pointers.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 7: Pointers.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Chapter 6 Structures Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
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++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Computer Organization and Design Pointers, Arrays and Strings in C
CNG 140 C Programming (Lecture set 10)
Lecture 9 Structure 1. Concepts of structure Pointers of structures
CNG 140 C Programming (Lecture set 8)
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Programming in C Pointer Basics.
Programming in C Pointer Basics.
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
Structures, Unions, and Enumerations
Presentation transcript:

CNG 140 C Programming (Lecture set 10) Spring Chapter 12 Structures

CNG 140 C Programming2 Structures: Objectives Single Structures Arrays of Structures Passing and Returning Structures Common Programming and Compiler Errors

CNG 140 C Programming3 Introduction Each data item listed in the following table is an entity by itself, called a data field Together, all the data fields form a single unit called a record –In C, a record is referred to as a structure

CNG 140 C Programming4 Fields and a Record Name: Surname: StudentID: Department: Class: Address: TelNo: Address:

CNG 140 C Programming5 Fields and a Record Name: Tayfun Surname: Akin StudentID: Department: CNG Class:1 Address: e TelNo: Address: METU-NCC

CNG 140 C Programming6 Introduction (continued) A structure’s form consists of the symbolic names, data types, and arrangement of individual data fields in the record The structure’s contents consist of the actual data stored in the symbolic names

CNG 140 C Programming7 Single Structures Structure definition in C: struct { int month; int day; int year; } birth; –Reserves storage for the individual data items listed in the structure –The three data items are the members of the structure Assigning actual data values to the data items of a structure is called populating the structure

CNG 140 C Programming8 spacing of a structure definition is not rigid Single Structures (continued)

CNG 140 C Programming9 Single Structures (continued) Multiple variables can be defined in one statement struct {int month; int day; int year;} birth, current; Creates two structures having the same form The form of the structure can have type name proceeding the variable names –The list of structure members must be preceded by a user- selected structure type name struct Date { int month; int day; int year; }; Date is the structure type name

CNG 140 C Programming10 By convention the first letter of user-selected structure type names is uppercase Single Structures (continued)

CNG 140 C Programming11 Single Structures (continued) Initialization of structures follows the same rules as for the initialization of arrays: –struct Date birth = {12, 28, 1987}; Structure members can be of any data type struct PayRecord { char name[20]; int idNum; double regRate; /* regular rate */ double otRate; /* overtime rate */ }; struct PayRecord employee = {"H. Price", 12387, 15.89, 25.50};

CNG 140 C Programming12 Single Structures (continued) Advantage of structures is when the same structure type is used in a list many times Individual members can be arrays and structures struct { char name[20]; struct Date birth; } person; –Example: person.name[4]

CNG 140 C Programming13 Arrays of Structures Structure is a powerful data structure when used with arrays. It would be possible to have heterogeneity in arrays which would otherwise be inconvenient…

CNG 140 C Programming14 Arrays of Structures: example

CNG 140 C Programming15 Arrays of Structures (continued)

CNG 140 C Programming16 struct PayRecord struct PayRecord /* construct a global structure type*/ { int id; char name[20]; double rate; };

CNG 140 C Programming17 Inner braces are not necessary Arrays of Structures (continued)

CNG 140 C Programming18 Arrays of Structures (continued) Without explicit initializers, the numeric elements of both static and external arrays or structures are initialized to 0 (or nulls)

CNG 140 C Programming19 Example This listing uses a structure type which is slightly different to PersonalData in that string pointers are used instead of arrays. This allows more convenient handling of real-life strings. /*********************************************************/ /* */ /* Structures Demo */ /* */ /*********************************************************/ /* Simple program to initialize some structures */ /* and to print them out again. Does no error */ /* checking, so be wary of string sizes etc.. */ #include #define NAMESIZE 30 #define ADDRSIZE 80 #define NOOFPERSONS 20 #define NEWLINE() putchar('\n');

CNG 140 C Programming20 Example: cont. /*********************************************************/ typedef struct { char *Name; char *Address; int YearOfBirth; int MonthOfBirth; int DayOfBirth; } PersonDat; /*********************************************************/

CNG 140 C Programming21 Example : cont. main () /* Make some records */ { PersonDat record[NOOFPERSONS]; PersonDat PersonalDetails(); int person; printf ("Birth Records For Employees"); printf ("\n "); printf ("\n\n"); printf ("Enter data\n"); for (person = 0; person < NOOFPERSONS; person++) { record[person] = PersonalDetails(); NEWLINE(); } DisplayRecords (record); }

CNG 140 C Programming22 Example : cont. /*********************************************************/ PersonDat PersonalDetails() /* No error checking! */ { PersonDat dat; char strbuff[ADDRSIZE], *malloc(); printf ("Name :"); dat.Name = malloc(NAMESIZE); strcpy (dat.Name,gets(strbuff)); printf ("Address :"); dat.Address = malloc(ADDRSIZE); strcpy (dat.Address,gets(strbuff)); printf ("Year of birth:"); dat.YearOfBirth = getint (1900,2007); printf ("Month of birth:"); dat.MonthOfBirth = getint (1,12); printf ("Day of birth:"); dat.DayOfBirth = getint(1,31); return (dat); }

CNG 140 C Programming23 Example : cont. /**********************************************************/ DisplayRecords (rec) PersonDat rec[NOOFPERSONS]; { int pers; for (pers = 0; pers < NOOFPERSONS; pers++) { printf ("Name : %s\n", rec[pers].Name); printf ("Address : %s\n", rec[pers].Address); printf("Date of Birth: %1d/%1d/%1d\n",rec[pers].DayOfBirth, rec[pers].MonthOfBirth,rec[pers].YearOfBirth); NEWLINE(); }

CNG 140 C Programming24 Example : cont. /* Toolkit */ getint (a,b) /* return int between a and b */ int a,b; { int p, i = a - 1; for (p=0; ((a > i) || (i > b)); p++) { printf ("? : "); scanf ("%d",&i); } return (i); }

CNG 140 C Programming25 Passing Structures Individual structure members may be passed to a function in the same manner as any scalar variable –display(emp.idNum) –calcPay(emp.payRate,emp.hours); On most compilers, complete copies of all members of a structure can also be passed to a function by including the name of the structure as an argument to the called function –calcNet(emp);

CNG 140 C Programming26 Pass by value Passing Structures (continued) Emp and temp are two different structures of the same type

CNG 140 C Programming27 Passing and Returning Structures using by reference notation or pointer A structure can be passed by reference –calcNet(&emp); –double calcNet(struct Employee *pt) –(*pt).idNum or *pt->idNum indicates that the address of the structure is retrieved before the element is fetched.. (*pt).x and *pt->x are the same thing

CNG 140 C Programming28 Passing and Returning Structures: example

CNG 140 C Programming29 Passing and Returning Structures (continued) ++ and -- can be applied to structures –++pt->hours \\ adds 1 to the hours member –(pt++)->hours \\increment the address after the hours is accessed\\increment –(++pt)->hours \\ increment the address before accessing hours

CNG 140 C Programming30 Passing and Returning Structures (continued)

CNG 140 C Programming31 Returning Structures

CNG 140 C Programming32 Returning Structures (continued)

CNG 140 C Programming33 Exercise a,b Write a C function larger() that returns the later date of any two given dates in mm/dd/yyyy

CNG 140 C Programming34 Exercise a,b /* Description: 12.3 Exercise 4b */ #include struct Date { int month; int day; int year; }; struct Date larger(struct Date, struct Date );

CNG 140 C Programming35 Exercise a,b int main() { /* use any two dates a and b struct Date a = {10, 9, 2001}; struct Date b = {11, 3, 2001}; struct Date c; printf ( "Date a: %d/", a.month ); printf ( "%d/%d\n", a.day, a.year ); printf ( "\nDate b: %d/", b.month ); printf ( "%d/%d\n", b.day, b.year ); c = larger(a, b); printf ( "\nThe larger of these two Dates is %d/", c.month ); printf ( "%d/%d\n", c.day, c.year ); return 0; }

CNG 140 C Programming36 Exercise a,b struct Date larger(struct Date date1, struct Date date2) { /* Assume that all months have 30 days and all years have 365 days */ long d1 = date1.day + 30*(date1.month-1) + 365*date1.year; long d2 = date2.day + 30*(date2.month-1) + 365*date2.year; if (d1 > d2) return date1; else return date2; }

CNG 140 C Programming37 Unions A union is a data type that reserves the same area in memory for two or more variables union { char key; int num; double price; } val; –Each of these types, but only one at a time, can actually be assigned to the union variable –A union reserves sufficient memory locations to accommodate its largest member’s data type

CNG 140 C Programming38 Unions (continued) Individual union members are accessed using the same notation as structure members Typically, a second variable keeps track of the current data type stored in the union switch(uType) { case ‘c’: printf("%c", val.key); break; case ‘i’: printf("%d", val.num); break; case ‘d’: printf("%f", val.price); break; default : printf("Invalid type : %c", uType); }

CNG 140 C Programming39 Unions (continued) A type name can be associated with a union to create templates union DateTime { long days; double time; }; union DateTime first, second, *pt; Pointers to unions use the same notation as pointers to structures Unions may be members of structures and arrays; structures, arrays, and pointers may be members of unions

CNG 140 C Programming40 Unions (continued) struct { char uType; union { char *text; double rate; } uTax; } flag; rate is referenced as flag.uTax.rate The first character of the string whose address is stored in the pointer text is accessed as *flag.uTax.text

CNG 140 C Programming41 UNION #define AUTO 1 #define BOAT 2 #define PLANE 3 #define SHIP 4

CNG 140 C Programming42 UNION struct automobile { /* structure for an automobile */ int tires; int fenders; int doors; }; typedef struct { /* structure for a boat or ship */ int displacement; char length; } BOATDEF;

CNG 140 C Programming43 UNION struct { char vehicle; /* what type of vehicle */ int weight; /* gross weight of vehicle */ union { /* type-dependent data */ struct automobile car; /* part 1 of the union */ BOATDEF boat; /* part 2 of the union */ struct { char engines; int wingspan; } airplane; /* part 3 of the union */ BOATDEF ship; /* part 4 of the union */ } vehicle_type; int value; /* value of vehicle in dollars */ char owner[32]; /* owners name */ } ford, sun_fish, piper_cub; /* three variable structures */

CNG 140 C Programming44 UNION main() { ford.vehicle = AUTO; ford.weight = 2742; /* with a full gas tank */ ford.vehicle_type.car.tires = 5; /* including the spares */ ford.vehicle_type.car.doors = 2; sun_fish.value = 3742; /* trailer not included */ sun_fish.vehicle_type.boat.length = 20; piper_cub.vehicle = PLANE; piper_cub.vehicle_type.airplane.wingspan = 27; if (ford.vehicle == AUTO) /* which it is in this case */ printf("?The ford has %d tires./n",ford.vechicle_type.car.tires); if (piper_cub.vehicle == AUTO) /* which it is not in this case */ printf("The plane has %d tires.\n",piper_cub.vechicle_type. car.tires); }

CNG 140 C Programming45 Common Programming Errors Attempting to use structures and unions, as complete entities, in relational expressions Assigning an incorrect address to a pointer that is a member of a structure or union Storing one data type in a union and accessing it by the wrong variable name can result in an error that is particularly troublesome to locate

CNG 140 C Programming46 Common Compiler Errors

CNG 140 C Programming47 Summary A structure allows individual variables to be grouped under a common variable name A structure type name can be used to create a generalized structure type describing the form and arrangement of elements in a structure Structures are particularly useful as elements of arrays

CNG 140 C Programming48 Summary (continued) Individual members of a structure are passed to a function in the manner appropriate to the data type of the member being passed Structure members can be any valid C data type, including structures, unions, arrays, and pointers Unions are declared in the same manner as structures