Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 19-2 Data Structures A data structure.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Linked Lists.
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Dynamic memory allocation
An introduction to pointers in c
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.
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
Programming and Data Structure
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.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
User-Level Memory Management in Linux Programming
Linked Lists
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
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.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title: Overview of Data Structure.
CMPE13 Cyrus Bazeghi Chapter 19 Data Structures. CMPE Data Structures A data structure is a particular organization of data in memory. –We want.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Function Smaller, simpler, subcomponent.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
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.
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:
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Chapter 17 Free-Space Management Chien-Chung Shen CIS, UD
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Data Structure & Algorithms
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
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.
C Structures and Memory Allocation
Dynamic Allocation Review Structure and list processing
Lectures linked lists Chapter 6 of textbook
Chapter 19 Data Structures
Chapter 19 Data Structures
Chapter 19 Data Structures
Chapter 19 Data Structures
Chapter 16 Linked Structures
Data Structures & Algorithms
C Structures and Memory Allocation
Module 13 Dynamic Memory.
Chapter 19 Data Structures -struct -dynamic memory allocation
Chapter 16 Pointers and Arrays
Presentation transcript:

Chapter 19 Data Structures

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure is a particular organization of data in memory. We want to group related items together. We want to organize these data bundles in a way that is convenient to program and efficient to execute. An array is one kind of data structure. In this chapter, we look at two more: struct – directly supported by C linked list – built from struct and dynamic allocation

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Structures in C A struct is a mechanism for grouping together related data items of different types. Recall that an array groups items of a single type. Example: We want to keep track of weather data for the past 100 days. For each day, we can define the following data: int highTemp; int lowTemp; double precip; double windSpeed; int windDirection; We can use a struct to group these data together for each day.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Defining a Struct We first need to define a new type for the compiler and tell it what our struct looks like. struct w_type { int highTemp; int lowTemp; double precip; double windSpeed; int windDirection; }; This tells the compiler how big our struct is and how the different data items (“members”) are laid out in memory. But it does not allocate any memory.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Declaring and Using a Struct To allocate memory for a struct, we declare a variable using our new data type. struct w_type day; Memory is allocated, and we can access individual members of this variable: day.highTemp = 32; day.lowTemp = 22; A struct’s members are laid out in memory in the order specified by the struct definition. day.highTemp day.lowTemp day.precip day.windSpeed day.windDirection 32 22

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Defining and Declaring at Once You can both define and declare a struct at the same time. struct w_type { int highTemp; int lowTemp; double precip; double windSpeed; int windDirection; } day; And you can still use the w_type name to declare other structs. struct w_type day2;

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display typedef C provides a way to define a data type by giving a new name to a predefined type. Syntax: typedef ; Examples: typedef int Color; typedef struct w_type WeatherData; typedef struct ab_type { int a; double b; } ABGroup;

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Using typedef This gives us a way to make code more readable by giving application-specific names to types. Color pixels[500]; WeatherData day1, day2; Typical practice: Put typedef’s into a header file, and use type names in main program. If the definition of Color/WeatherData changes, you might not need to change the code in your main program file.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Generating Code for Structs Suppose our program starts out like this: int x; WeatherData day; int y; day.highTemp = 12; day.lowTemp = 1; day.windDirection = 3;... The next slide shows LC-2 code for these assignments. x day.highTemp day.lowTemp day.precip day.windSpeed day.windDirection y offset =

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Code for Structs ; day.highTemp = 12; AND R1, R1, #0 ; R1 = 12 ADD R1, R1, #12 ADD R0, R6, #4 ; R0 has base addr of day ADD R0, R0, #0 ; add offset to highTemp STR R1, R0, #0 ; store value into day.highTemp ; day.lowTemp = 1; AND R1, R1, #0 ; R1 = 1 ADD R1, R1, #1 ADD R0, R6, #4 ; R0 has base addr of day ADD R0, R0, #1 ; add offset to lowTemp STR R1, R0, #0 ; store value into day.lowTemp ; day.windDirection = 3; AND R1, R1, #0 ; R1 = 3 ADD R1, R1, #3 ADD R0, R6, #4 ; R0 has base addr of day ADD R0, R0, #10 ; add offset to windDirection STR R1, R0, #0 ; store value into day.windDirection

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Array of Structs Can declare an array of structs: WeatherData days[100]; Each array element is a struct (7 words, in this case). To access member of a particular element: days[34].highTemp = 97; Because the [] and. operators are at the same precedence, and both associate left-to-right, this is the same as: (days[34]).highTemp = 97;

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointer to Struct We can declare and create a pointer to a struct: WeatherData *dayPtr; dayPtr = &days[34]; To access a member of the struct addressed by dayPtr: (*dayPtr).highTemp = 97; Because the. operator has higher precedence than *, this is NOT the same as: *dayPtr.highTemp = 97; C provides special syntax for accessing a struct member through a pointer: dayPtr->highTemp = 97;

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Passing Structs as Arguments Unlike an array, a struct is always passed by value into a function. This means the struct members are copied to the function’s activation record, and changes inside the function are not reflected in the calling routine’s copy. Most of the time, you’ll want to pass a pointer to a struct. int InputDay(WeatherData *day) { printf(“High temp in deg F: ”); scanf(“%d”, &day->highTemp); printf(“Low temp in deg F: ”); scanf(“%d”, &day->;lowTemp);... }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Dynamic Allocation Suppose we want our weather program to handle a variable number of days – as many as the user wants to enter. We can’t allocate an array, because we don’t know the maximum number of days that might be required. Even if we do know the maximum number, it might be wasteful to allocate that much memory because most of the time only a few days’ worth of data is needed. Solution: Allocate storage for data dynamically, as needed.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display malloc The Standard C Library provides a function for allocating memory at run-time: malloc. void *malloc(int numBytes); It returns a generic pointer ( void* ) to a contiguous region of memory of the requested size (in bytes). The bytes are allocated from a region in memory called the heap. The run-time system keeps track of chunks of memory from the heap that have been allocated.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Using malloc To use malloc, we need to know how many bytes to allocate. The sizeof operator asks the compiler to calculate the size of a particular type. days = malloc(n * sizeof(WeatherData)); We also need to change the type of the return value to the proper kind of pointer – this is called “casting.” days = (WeatherData*) malloc(n* sizeof(WeatherData));

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example int numberOfDays; WeatherData *days; printf(“How many days of weather?”); scanf(“%d”, &numberOfDays); days = (WeatherData*) malloc(sizeof(WeatherData) * numberOfDays); if (days == NULL) { printf(“Error in allocating the data array.\n”);... } days[0].highTemp =... If allocation fails, malloc returns NULL (zero). Note: Can use array notation or pointer notation.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display free Once the data is no longer needed, it should be released back into the heap for later use. This is done using the free function, passing it the same address that was returned by malloc. void free(void*); If allocated data is not freed, the program might run out of heap memory and be unable to continue.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display The Linked List Data Structure A linked list is an ordered collection of nodes, each of which contains some data, connected using pointers. Each node points to the next node in the list. The first node in the list is called the head. The last node in the list is called the tail. Node 0Node 1Node 2 NULL

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Linked List vs. Array A linked list can only be accessed sequentially. To find the 5 th element, for instance, you must start from the head and follow the links through four other nodes. Advantages of linked list: Dynamic size Easy to add additional nodes as needed Easy to add or remove nodes from the middle of the list (just add or redirect links) Advantage of array: Can easily and quickly access arbitrary elements

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example: Car Lot Create an inventory database for a used car lot. Support the following actions: Search the database for a particular vehicle. Add a new car to the database. Delete a car from the database. The database must remain sorted by vehicle ID. Since we don’t know how many cars might be on the lot at one time, we choose a linked list representation.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display CarNode Each car has the following characterics: vehicle ID, make, model, year, mileage, cost. Because it’s a linked list, we also need a pointer to the next node in the list: typedef struct car_node CarNode; struct car_node { int vehicleID; char make[20]; char model[20]; int year; int mileage; double cost; CarNode *next; /* ptr to next car in list */ }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Scanning the List Searching, adding, and deleting all require us to find a particular node in the list. We scan the list until we find a node whose ID is >= the one we’re looking for. CarNode *ScanList(CarNode *head, int searchID) { CarNode *previous, *current; previous = head; current = head->next; /* Traverse until ID >= searchID */ while ((current!=NULL) && (current->vehicleID next; } return previous; }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Adding a Node Create a new node with the proper info. Find the node (if any) with a greater vehicleID. “Splice” the new node into the list: Node 0Node 1Node 2 NULL new node

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Excerpts from Code to Add a Node newNode = (CarNode*) malloc(sizeof(CarNode)); /* initialize node with new car info */... prevNode = ScanList(head, newNode->vehicleID); nextNode = prevNode->next; if ((nextNode == NULL) || (nextNode->vehicleID != newNode->vehicleID)) prevNode->next = newNode; newNode->next = nextNode; } else { printf(“Car already exists in database.”); free(newNode); }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Deleting a Node Find the node that points to the desired node. Redirect that node’s pointer to the next node (or NULL). Free the deleted node’s memory. Node 0Node 1Node 2 NULL

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Excerpts from Code to Delete a Node printf(“Enter vehicle ID of car to delete:\n”); scanf(“%d”, vehicleID); prevNode = ScanList(head, vehicleID); delNode = prevNode->next; if ((delNode != NULL) && (delNode->vehicleID == vehicleID)) prevNode->next = delNode->next; free(delNode); } else { printf(“Vehicle not found in database.\n”); }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Building on Linked Lists The linked list is a fundamental data structure. Dynamic Easy to add and delete nodes The concepts described here will be helpful when learning about more elaborate data structures: Trees Hash Tables Directed Acyclic Graphs...