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

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Stacks, Queues, and Linked Lists
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.
Dynamic memory allocation
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Stack & Queues COP 3502.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Introduction to Memory Management. 2 General Structure of Run-Time Memory.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Module R2 Overview. Process queues As processes enter the system and transition from state to state, they are stored queues. There may be many different.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Chapter 10.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
CNG 140 C Programming (Lecture set 10) Spring Chapter 12 Structures.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Runtime Environments Compiler Construction Chapter 7.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
(1 - 1) Introduction to C Data Structures & Abstract Data Types Instructor - Andrew S. O’Fallon CptS 122 (August 26, 2015) Washington State University.
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Data structures Abstract data types Java classes for Data structures and ADTs.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec.
Introduction to Data Structures Systems Programming Concepts.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Programming Practice 3 - Dynamic Data Structure
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.
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
STACKS & QUEUES for CLASS XII ( C++).
Chapter 12 – Data Structures
Dynamic Allocation Review Structure and list processing
12 C Data Structures.
Stacks and Queues.
CSCE 210 Data Structures and Algorithms
Popping Items Off a Stack Lesson xx
Dynamic Memory Allocation
Review & Lab assignments
Introduction to Data Structure
(1 - 2) Introduction to C Data Structures & Abstract Data Types
Presentation transcript:

CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures

CNG140 C Programming2 Objectives Introduction to Linked Lists Dynamic Memory Allocation Stacks Queues Dynamically Linked Lists Common Programming and Compiler Errors

CNG140 C Programming3 Introduction Dynamic memory allocation: an alternative to fixed memory allocation in which memory space grows or diminishes during program execution Dynamic memory allocation makes it unnecessary to reserve a fixed amount of memory for a scalar, array, or structure variable in advance –Also known as run-time allocation –Requests are made for allocation and release of memory space while the program is running

CNG140 C Programming4 Introduction to Linked Lists An array of structures can be used to insert and delete ordered structures, but this is not an efficient use of memory –Better alternative: a linked list Linked list: set of structures, each containing at least one member whose value is the address of the next logically ordered structure in the list –Also known as self-referencing structures

CNG140 C Programming5 Introduction to Linked Lists (continued)

CNG140 C Programming6 Introduction to Linked Lists (continued)

CNG140 C Programming7 Introduction to Linked Lists (continued) A NULL acts as a sentinel or flag to indicate when the last structure has been processed In addition to an end-of-list sentinel value, we must provide a special pointer for storing the address of the first structure in the list

CNG140 C Programming8 Introduction to Linked Lists (continued)

CNG140 C Programming9 A structure can contain any data type, including a pointer. A pointer member of a structure is used like any other pointer variable. Introduction to Linked List: Pointer Example

CNG140 C Programming10 is evaluated as (t1.nextaddr)->name it can be replaced by (*t1.nextaddr).name Introduction to Linked Lists: Link List Example

CNG140 C Programming11 Introduction to Linked Lists (continued)

CNG140 C Programming12 Introduction to Linked Lists (continued) Disadvantage: exactly three structures are defined in main() by name, and storage for them is reserved at compile time

CNG140 C Programming13 Introduction to Linked Lists (continued) can be replaced by while(!contents)

CNG140 C Programming14 Dynamic Memory Allocation

CNG140 C Programming15 Dynamic Memory Allocation (continued) The malloc() and calloc() functions can frequently be used interchangeably –The advantage of calloc() is that it initializes all newly allocated numeric memory to 0 and character allocated memory to NULL –We use malloc() because it is the more general purpose of the two functions –malloc(10*sizeof(char)) or calloc(10,sizeof(char)) requests enough memory to store 10 characters The space allocated by malloc() comes from the computer’s heap

CNG140 C Programming16 … Necessary because malloc() returns void Dynamic Memory Allocation (continued)

CNG140 C Programming17 Dynamic Memory Allocation (continued) malloc() is more typically used for dynamically allocating memory for structures struct OfficeInfo *Off; /* request space for one structure */ Off = (struct OfficeInfo *) malloc(sizeof(struct OfficeInfo)); /* check that space was allocated */ if (Off == (struct OfficeInfo*) NULL) { printf("\nAllocation failed\n"); exit(1); }

CNG140 C Programming18 Example: Structure and Dynamic memory allocation This listing uses a structure type PersonalData and dynamic memory allocation

CNG140 C Programming19 Example /*********************************************************/ /* */ /* 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');

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

CNG140 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); }

CNG140 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); }

CNG140 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(); }

CNG140 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); }

CNG140 C Programming25 Stacks Stack: special type of linked list in which objects can only be added to and removed from the top of the list –Last-in, first-out (LIFO) list In a true stack, the only item that can be seen and accessed is the top item

CNG140 C Programming26 Stacks (continued)

CNG140 C Programming27 Stack Implementation Creating a stack requires the following four components: –A structure definition –A method of designating the current top stack structure –An operation for placing a new structure on the stack –An operation for removing a structure from the stack

CNG140 C Programming28 PUSH and POP PUSH (add a new structure to the stack) Dynamically create a new structure Put the address in the top-of-stack pointer into the address field of the new structure Fill in the remaining fields of the new structure Put the address of the new structure into the top-of-stack pointer POP (remove a structure from the top of the stack) Move the structure contents pointed to by the top-of-stack pointer into a work area Free the structure pointed to by the top-of-stack pointer Move the address in the work area address field into the top- of-stack pointer

CNG140 C Programming29 PUSH and POP (continued)

CNG140 C Programming30 PUSH and POP (continued)

CNG140 C Programming31 PUSH and POP (continued)

CNG140 C Programming32 PUSH and POP (continued)

CNG140 C Programming33 PUSH and POP (continued) A sample run using Program 13.5 produced the following: Enter as many names as you wish, one per line To stop entering names, enter a single x Enter a name: Jane Jones Enter a name: Bill Smith Enter a name: Jim Robinson Enter a name: x The names popped from the stack are: Jim Robinson Bill Smith Jane Jones

CNG140 C Programming34 Queues A second important data structure that relies on linked structures is called a queue –Items are removed from a queue in the order in which they were entered –It is a first in, first out (FIFO) structure

CNG140 C Programming35 Queues (continued)

CNG140 C Programming36 Queues (continued)

CNG140 C Programming37 Enque and Serve Enqueueing: placing a new item on top of the queue Serving or dequeing: removing an item from a queue

CNG140 C Programming38 Enque and Serve (continued)

CNG140 C Programming39 Enque and Serve (continued) Enqueue (add a new structure to an existing queue) Dynamically create a new a structure Set the address field of the new structure to a NULL Fill in the remaining fields of the new structure Set the address field of the prior structure (which is pointed to by the queueIn pointer) to the address of the newly created structure Update the address in the queueIn pointer with the address of the newly created structure

CNG140 C Programming40 Enque and Serve (continued)

CNG140 C Programming41 Enque and Serve (continued) Serve (remove a structure from an existing queue) Move the contents of the structure pointed to by the queueOut pointer into a work area Free the structure pointed to by the queueOut pointer Move the address in the work area address field into the queueOut pointer

CNG140 C Programming42 Enque and Serve (continued)

CNG140 C Programming43 Enque and Serve (continued)

CNG140 C Programming44 Enque and Serve (continued)

CNG140 C Programming45 Enque and Serve (continued)

CNG140 C Programming46 Enque and Serve (continued)

CNG140 C Programming47 Enque and Serve (continued) A sample run using Program 13.6 produced the following: Enter as many names as you wish, one per line To stop entering names, enter a single x Enter a name: Jane Jones Enter a name: Bill Smith Enter a name: Jim Robinson Enter a name: x The names served from the queue are: Jane Jones Bill Smith Jim Robinson

CNG140 C Programming48 Dynamically Linked Lists Both stacks and queues are examples of linked lists in which elements can only be added to and removed from the ends of the list In a dynamically linked list, this capability is extended to permit adding or deleting a structure from anywhere within the list Such a capability is extremely useful when structures must be kept within a specified order

CNG140 C Programming49 Common Programming Errors Not checking the return codes provided by malloc() and realloc() Not correctly updating all relevant pointer addresses when adding or removing structures from dynamically created stacks, queues, and linked lists Forgetting to free previously allocated memory space when the space is no longer needed

CNG140 C Programming50 Common Programming Errors (continued) Not preserving the integrity of the addresses contained in the top-of-stack pointer, queue-in, queue-out, and list pointer when dealing with a stack, queue, and dynamically linked list, respectively Related to the previous error is the equally disastrous one of not correctly updating internal structure pointers when inserting and removing structures from a stack, queue, or dynamically linked list

CNG140 C Programming51 Common Compiler Errors

CNG140 C Programming52 Common Compiler Errors (continued)

CNG140 C Programming53 Summary An alternative to fixed memory allocation for variables at compile time is the dynamic allocation of memory at run time malloc() reserves a requested number of bytes and returns a pointer to the first reserved byte realloc() operates in a similar fashion as malloc() except it is used to expand or contract an existing allocated space free() is used to deallocate previously allocated memory space

CNG140 C Programming54 Summary (continued) A stack is a list consisting of structures that can only be added and removed from the top of the list A queue is a list consisting of structures that are added to the top of the list and removed from the bottom of the list A dynamically linked list consists of structures that can be added or removed from any position in the list