22&23-2 Understand how structure data types are implemented in C. Use “.” operator to access members of a structure. See how to declare pointers to structure.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

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.
Programming and Data Structure
Programming Languages and Paradigms The C Programming 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.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7: User-Defined Functions II
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
11-2 Identify the parts of the “main” function, which include Preprocessor Directives main function header main function body which includes Declaration.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
Lecture 7 C Pointers Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
21-2 Understand various methods of sorting. Use the qsort function to sort. Binary search Related Chapter: ABC 8.5.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
16&17-2 Grasp the concept of top-down programming Identify Function Headers and Prototypes Understand when and where prototypes used Understand how arguments.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
C Programming Tutorial – Part I CS Introduction to Operating Systems.
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 23P. 1Winter Quarter Structs and Enumeration Lecture 23.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Spring 2005, Gülcihan Özdemir Dağ Lecture 11, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 11 Outline 11.1.
Structures Combining data types into a logical groupings.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
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.
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
Data Structure and c K.S.Prabhu Lecturer All Deaf Educational Technology.
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.
Chapter 11 – Pointer Variables. Declaring a Pointer Variable u Declared with data type, * and identifier type* pointer_variable; u * follows data type.
+ 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.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
2/23/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 9 (C-3)
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
Chapter 11 Structures, Unions and Typedef 11.1 Structures Structures allow us to group related data items of different types under a common name. The individual.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Lesson #8 Structures Linked Lists Command Line Arguments.
Computer Science 210 Computer Organization
CS1010 Programming Methodology
Student Book An Introduction
User-Defined Functions
Computer Science 210 Computer Organization
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Programming Languages and Paradigms
Presentation transcript:

22&23-2 Understand how structure data types are implemented in C. Use “.” operator to access members of a structure. See how to declare pointers to structure variables. Use “ -> ” operator to access members of a structure when using pointers. Related Chapter: ABC 9.1 – 9.6

22& Problem Definition Write a program that keeps an inventory for an auto parts store. Previously, the information for each auto part was kept on an index card. Each index card had the following fields: id --- a unique identifier for your parts name ---- a category name for the part, like “air filter” quantity --- the quantity in stock price ---- retail price The auto parts store can have as many as 30,000 different parts. Your program should define a new C data type named “part”. You will declare 30,000 variables of data type “part”. Each variable (like an index card) should hold the values for all of the fields listed above.

22& Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) We first define a new data type “part”. Then in main we will declare an array of 30,000 variables each of data type “part”. Your program will display a menu with the following choices: 0. Exit 1. Display the parts. 2. Find a part. 3. Enter information for a new part. For each menu item we will write a corresponding function to carry out that menu option. Input = A choice from the menu. For menu choice 2. the user must supply the part “id”. For choice 3. the user must supply all the information for the new auto part. Output= For choice 1. all the fields of all the parts will be displayed on the computer screen.

#include #include #define MAX_SIZE typedef struct { /* user defined data-type called part */ int id; /* this is a definition*/ char name[32]; /* no variables are declared */ int quantity; /* location is outside any block */ float price; } part; int menu(void) { int choice; /* C merges strings */ printf("\n0. Exit \n" "1. Display the parts.\n" "2. Find a part.\n" "3. Enter information for a new part.\n" "choice: "); scanf("%i",&choice); return choice; } /* end of menu */ /* continued on next slide */

void display_one_part(part p) { printf(“%-9i %-31s %-5i $%.2f \n”, p.id, p.name, p.quantity, p.price); } /* end of display_one_part */ int display_parts(part parts[],int count) { int i; for(i = 0; i < count; ++i) display_one_part(parts[i]); } /* end of display_parts */ /* continued on next slide */

int find_part(part parts[], int count) { int i, id_sought; /* return the index of the array for given id */ /* return the value -1 if id_sought not found */ printf("Enter an id number: "); scanf("%i",&id_sought); for(i= 0; i < count; ++i) if (id_sought == parts[i].id) return i; return -1; } /* end of find_part */ /* continued on next slide */

int add_part(part parts[],int count, int max_size) { int i; if (count == max_size) { printf(“insufficient space to add another part\n”); return count; } /* use C regular expression [ ] to read a string with blanks*/ /* ^ means NOT */ printf("Enter one part in format \n" printf(" id; part name ; quantity; price \n"); scanf(" %i; %[^;]; %i; %f", &parts[count].id, parts[count].name, &parts[count].quantity, &parts[count].price); return count+1; } /* end of add_part */ /* continued on next slide */

void main(void) { int choice, index; part parts[MAX_SIZE]; /* MAX_SIZE is a constant = */ int count = 0; /* actual number of parts in array */ while(1) /* infinite loop */ { choice = menu(); switch(choice) { case 0: printf("Bye bye!\n"); return; case 1: display_parts(parts,count); break; case 2: index = find_part(parts,count); if ( index != -1) display_one_part(parts[index]); else printf("Part not found!\n"); break; case 3: count = add_part(parts,count,MAX_SIZE); } /* end of switch */ } /* end of while */ } /* end of main */

22&23-10 (see demo in lecture)

22&23-11 To set up a structure in C, we need to (1) Define a structure type. There are several ways to do this in C. In general, we will use the typedef mechanism to do this. (2) Declare variables to be of that type. Note: The built-in data types (e.g. int, float, char,…) can be used to declare variables in the C language. These data types don’t have to be defined by the user. Structures provide the user with the means to define custom designed data types.

22&23-12 You can use the typedef mechanism in C to create an alias for a structure. The code above names “part” as a alias for, typedef struct { int id; char name[32]; int quantity; float price; } part; struct { int id; char name[32]; int quantity; float price; };

22&23-13 Structure definitions do not reserve storage, they are used to define a new data type. For example, the code above doesn’t allocate any storage. It doesn’t reserve memory for id, name, quantity or price --- the fields or members of the structure. Also, part is not a variable its like int, char,float, double. typedef struct { int id; char name[32]; int quantity; float price; } part;

22&23-14 Once you have defined a new data type, you can declare (and initialize) a variable of this data type as in, The variables p is declared to be of data type “part” where “part” is a synonym for the structure, part p ={1001,”Air Filter”, 100, 12.49}; Structure variables, like p above, are initialized in the same way you initialize an array. struct { int id; char name[32]; int quantity; float price; };

22&23-15 p.id “Air Filter” part p ={1001,”Air Filter”,100, 12.49}; After the declaration of p, the picture of memory looks like,.name 100.quantity.price 1000 Address typedef struct { int id; char name[32]; int quantity; float price; } part;

22&23-16 part parts[30000]; We can even declare an array of structure data type. typedef struct { int id; char name[32]; int quantity; float price; } part;

22&23-17 parts[0].id Here is a memory map showing the first two element in the array named parts..name.quantity.price 2000 Address parts[1].id.name.quantity.price

22&23-18 struct Part p = {1001,”Air Filter”, 100, 12.49}; A second, alternative method in using structures in C is to code the following immediately after the preprocessor directives as in slide 5, The name Part is called a “tag name”. In order to declare variable p you would write, struct Part { int id; char name[32]; int quantity; float price; };

22&23-19 A third, alternative method in using structures in C is to combine the struct and declaration of the variable in one statement. struct Part{ int id; char name[32]; int quantity; float price; } p = {1001, "Air Filter", 100, 12.49};

22&23-20 Structures provide the mechanism in C for grouping values of different data types. Example: typedef struct { int employeeID; float salary; int departmentID; char name[30]; /* not same as char * name; */ } Employee;

22&23-21 Accessing(storing and fetching) values from/to fields in the structure is accomplished with the "dot operator" (.), also called the "structure member operator ". Example: (From slide 14) p.id = 1001; /* use the. to access individual fields */ p.quantity = 100; Example: (From the previous slide) Employee emp1; /* declare a variable of type Employee */ emp1.employeeID = 1004; /* initialize the variable */ emp1.salary = ;

22&23-22 scanf("%f",&emp1.salary); /* you can also use scanf */ emp1.departmentID = 37; strcpy(emp1.name, "John");/* strcpy function */ scanf("%s",emp1.name); /* no & needed */ emp1.name[0] = ‘J’; /* this also works */ emp1.name[1] = ‘o’; emp1.name[2] = ‘h’; emp1.name[3] = ‘n’; emp1.name[4] = ‘\0’;

22&23-23 display_one_part(parts[i]); Function calls with an argument having a structure data-type are implemented as call-by-value. In this regard structures differ from arrays in that arrays are passed as call-by-reference. For example, in slide 6, function display_one_part is called with argument “parts[i]” of data-type part. The header for the function display_one_part, void display_one_part(part p) has one parameter, p. The variable p is “local” in scope to the function display_one_part. In call-by- value the value of parts[i] is copied into p. p is not a synonym for parts[i].

22&23-24 part find_part(part parts[], int count) { int i, id_sought; printf("Enter an id number: "); scanf("%i",&id_sought); for(i= 0; i < count; ++i) if (id_sought == parts[i].id) return parts[i]; } /* end of find_part */ Functions can return values of structure data-type. For example, in slide 7, we could modify the find_part function, so that it returns the actual part. Of course the above code won’t work if the user types an invalid part id. Also, the call to find_part in main would have to be modified in order for the program to work.

22& Problem Definition Write a program that reads in data for the elements in the periodic system, (e.g. Hydrogen, Helium,...) the name as a string, symbol as a string, atomic number as an int and atomic weight as a double. After the elements have been entered they are sorted using qsort in ascending alphabetical order and then printed back to the terminal. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) We have four values per atomic element: name,symbol,atomicNum and atomicWt Rather than using five separate arrays of 118 elements we will use one array AtomicElement of 118 elements. The data-type of AtomicElement is a user-defined structure named Element. Input = Input data from keyboard as above. Output= Sort the elements by atomic name, using qsort.

#include typedef struct { /* user defined data-type called Element */ char name[15]; /* this is a definition, no variables are declared */ char symbol[3];/* location of this definition is outside any block */ int atomicNum; double atomicWt; } Element; int cmpnames(Element * ptr1, Element * ptr2) ; /* prototype */ /* see explanation of the above in subsequent slides */ void main(void) { int num, i; Element AtomicElement[118]; /* AtomicElement is an array */ printf("How many elements are you going to enter? "); scanf("%i",&num); for(i=0;i<num;++i) { scanf("%s %s %i %lf",AtomicElement[i].name,AtomicElement[i].symbol,&AtomicElement[i].atomicNum,&AtomicElement[i].atomicWt); }

/* sort the arrays by name */ qsort(AtomicElement, num, sizeof(AtomicElement[0]), cmpnames); /* print the sorted array */ printf("\n"); for (i=0;i<num;++i) { printf("%s %s %i %.5lf ",AtomicElement[i].name,AtomicElement[i].symbol,AtomicElement[i].atomicNum,AtomicElement[i].atomicWt); printf("\n"); /* print one element per line */ } /* end of for */ } /* end of main */ int cmpnames(Element * ptr1, Element * ptr2) { return strcmp(ptr1->name, ptr2->name); /* why arrow and not dot? */ } /* end of cmpnames */

22&23-28 >./a.out How many elements are you going to enter?4 Hydrogen H Beryllium Be Gold Au Carbon C Beryllium Be Carbon C Gold Au Hydrogen H input output

22&23-29 strcmp(ptr1->name, ptr2->name) If the string ptr1->name name (alphabetically) then strcmp(ptr1->name, ptr2->name) has a negative value else if ptr1->name > ptr2->name then strcmp(ptr1->name, ptr2->name) has a positive value else if ptr1->name == ptr2->name then strcmp(ptr1->name, ptr2->name) has the value 0. These are the correct values we want to return to qsort and we do this by From Lecture 15 slide 21: strcmp(str1, str2) - returns a negative, zero or positive int depending on whether str1 is alphabetically less than, equal or greater than str2 respectively. qsort calls our function cmpnames and passes two addresses which are assigned to the pointer variables, ptr1 and ptr2. return strcmp(ptr1->name, ptr2->name);

22&23-30 Address 2030 prt1 ptr2 AtomicElement[0] “Beryllium” Address “Be” “Hydrogen”“H” AtomicElement[1] When qsort calls ‘cmpnames’

22&23-31 Address 2030 prt1 ptr2 AtomicElement[0] “Hydrogen” Address “H” “Beryllium”“Be” AtomicElement[1] After qsort calls ‘cmpnames’ Since ‘cmpnames’ function returns a positive value to the function ‘qsort’. The function ‘qsort’ does the work of swapping the 30 bytes of AtomicElement[0] with the 30 bytes of AtomicElement[1].

22&23-32 We can declare an array of the struct data type Autopart. AutoPart structArray[50]; declares structArray as an array which contains 50 cells (in memory) of type AutoPart. typedef struct { int id; char name[30]; } AutoPart; Given the data-type definition:

22&23-33 We can access the field in the structure with pointers and arrow operator “ -> ” (also called the indirect component selection operator ). The general format of the use of the arrow operator is: (see example on next slide) pointer_to_structure -> member_name

22&23-34 typedef struct { int employeeID; float salary; int departmentID; char name[30]; } Employee; Employee emp1,emp2; Employee *empPtr; /* pointer to data-type Employee */ emp1.employeeID = 1004; emp1.salary = ; emp1.departmentID = 37; strcpy(emp1.name, "John Smith"); empPtr = &emp1; /* empPtr now points to emp1 */ printf("employeeID is %i in department %i \n", empPtr->employeeID, empPtr->departmentID); emp2 = emp1;/* assigns values in ALL fields of emp1 to emp2 */

22&23-35 Rather than use the arrow operator we could use “ * ” the dereferencing operator. From the last example: printf("employeeID is %i in department %i \n", (*empPtr).employeeID, (*empPtr).departmentID); However, do not write: printf("employeeID is %i in department %i \n", *empPtr.employeeID, *empPtr.departmentID); because in C this means (see operator precedence rules) printf("emplayeeID is %i in department %i \n", *(empPtr.employeeID), *(empPtr.departmentID)); and these expressions are not equivalent. Why? Therefore, it may be “safer” to use the arrow operator, so that we don’t make the mistake shown above.