C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Similar documents
1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

C++ Programming Language

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

The C Programming Language course syllabus associate level

Illustration 1: Diagram of program function and data flow

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Data Structure with C

Lecture 12 Doubly Linked Lists (with Recursion)

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

The programming language C. sws1 1

/* File: blkcopy.c. size_t n

DATA STRUCTURES USING C

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

C Compiler Targeting the Java Virtual Machine

Using Heap Allocation in Intel Assembly Language

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

CSE 211: Data Structures Lecture Notes VII

8.5. <summary> Cppcheck addons Using Cppcheck addons Where to find some Cppcheck addons

Object Oriented Software Design II

ECS 165B: Database System Implementa6on Lecture 2

5 Arrays and Pointers

Sources: On the Web: Slides will be available on:

1 Abstract Data Types Information Hiding

7.1 Our Current Model

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Module 816. File Management in C. M. Campbell 1993 Deakin University

Data Structures Using C++ 2E. Chapter 5 Linked Lists

System Calls and Standard I/O

Raima Database Manager Version 14.0 In-memory Database Engine

Semantic Analysis: Types and Type Checking

Programming languages C

The Relational Data Model

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Stacks. Linear data structures

SQLITE C/C++ TUTORIAL

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

What is COM/DCOM. Distributed Object Systems 4 COM/DCOM. COM vs Corba 1. COM vs. Corba 2. Multiple inheritance vs multiple interfaces

Linked Lists Linked Lists, Queues, and Stacks

Numerical Algorithms Group

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Chapter 13 Storage classes

Help on the Embedded Software Block

LINKED DATA STRUCTURES

Implementation Aspects of OO-Languages

Object Oriented Software Design II

Lecture 1: Data Storage & Index

C Interview Questions

Client-server Sockets

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Lecture 11 Array of Linked Lists

How To Write Portable Programs In C

COS 318: Operating Systems. File Layout and Directories. Topics. File System Components. Steps to Open A File

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

MPI-Checker Static Analysis for MPI

Physical Data Organization

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

CSC 551: Web Programming. Fall 2001

Moving from CS 61A Scheme to CS 61B Java

SMTP-32 Library. Simple Mail Transfer Protocol Dynamic Link Library for Microsoft Windows. Version 5.2

TREE BASIC TERMINOLOGIES

Getting Started with the Internet Communications Engine

Introduction to Data Structures

Common Data Structures

arrays C Programming Language - Arrays

Variable Base Interface

Why you shouldn't use set (and what you should use instead) Matt Austern

A C Test: The 0x10 Best Questions for Would-be Embedded Programmers

Parallelization: Binary Tree Traversal

Chapter 13. Disk Storage, Basic File Structures, and Hashing

Free-Space Management

Binary Heap Algorithms

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Operating Systems CSE 410, Spring File Management. Stephen Wagner Michigan State University

Basic Programming and PC Skills: Basic Programming and PC Skills:

Linked List as an ADT (cont d.)

1 Posix API vs Windows API

Storage in Database Systems. CMPSCI 445 Fall 2010

Principles of Database Management Systems. Overview. Principles of Data Layout. Topic for today. "Executive Summary": here.

Tutorial on C Language Programming

10CS35: Data Structures Using C

Lecture Notes on Binary Search Trees

Binary Trees and Huffman Encoding Binary Search Trees

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

COMPUTER SCIENCE 1999 (Delhi Board)

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Transcription:

C Dynamic Data Structures University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

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 University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 2

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 represent an airborne aircraft: char flightnum[7]; int altitude; int longitude; int latitude; int heading; double airspeed; We can use a struct to group these data together for each plane. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 3

Defining a Struct We first need to define a new type for the compiler and tell it what our struct looks like. struct flighttype { char flightnum[7]; /* max 6 characters */ int altitude; /* in meters */ int longitude; /* in tenths of degrees */ int latitude; /* in tenths of degrees */ int heading; /* in tenths of degrees */ double airspeed; /* in km/hr */ }; 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. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 4

Declaring and Using a Struct To allocate memory for a struct, we declare a variable using our new data type. struct flighttype plane; plane.flightnum[0] Memory is allocated, and we can access individual members of this variable: plane.airspeed = 800.0; plane.altitude = 10000; A struct s members are laid out in the order specified by the definition. plane.flightnum[6] plane.altitude plane.longitude plane.latitude plane.heading plane.airspeed University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 5

Defining and Declaring at Once You can both define and declare a struct at the same time. struct flighttype { char flightnum[7]; /* max 6 characters */ int altitude; /* in meters */ int longitude; /* in tenths of degrees */ int latitude; /* in tenths of degrees */ int heading; /* in tenths of degrees */ double airspeed; /* in km/hr */ } maverick; And you can use the flighttype name to declare other structs. struct flighttype iceman; University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 6

typedef C provides a way to define a data type by giving a new name to a predefined type. Syntax: typedef <type> <name>; Examples: typedef int Color; typedef struct flighttype WeatherData; typedef struct ab_type { int a; double b; } ABGroup; University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 7

Using typedef This gives us a way to make code more readable by giving application-specific names to types. Color pixels[500]; Flight plane1, plane2; Typical practice: Put typedef s into a header file, and use type names in main program. If the definition of Color/Flight changes, you might not need to change the code in your main program file. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 8

Generating Code for Structs Suppose our program starts out like this: int x; Flight plane; int y; y plane.flightnum[0] plane.altitude = 0;... LC-3 code for this assignment: AND R1, R1, #0 ADD R0, R5, #-13 ; R0=plane STR R1, R0, #7 ; 8th word plane.flightnum[6] plane.altitude plane.longitude plane.latitude plane.heading plane.airspeed R5 University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 9 x

Array of Structs Can declare an array of structs: Flight planes[100]; Each array element is a struct (7 words, in this case). To access member of a particular element: planes[34].altitude = 10000; Because the [] and. operators are at the same precedence, and both associate left-to-right, this is the same as: (planes[34]).altitude = 10000; University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 10

Pointer to Struct We can declare and create a pointer to a struct: Flight *planeptr; planeptr = &planes[34]; To access a member of the struct addressed by dayptr: (*planeptr).altitude = 10000; Because the. operator has higher precedence than *, this is NOT the same as: *planeptr.altitude = 10000; C provides special syntax for accessing a struct member through a pointer: planeptr->altitude = 10000; University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 11

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 Collide(Flight *planea, Flight *planeb) { if (planea->altitude == planeb->altitude) {... } else return 0; } University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 12

Dynamic Allocation Suppose we want our weather program to handle a variable number of planes as many as the user wants to enter. We can t allocate an array, because we don t know the maximum number of planes 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 planes worth of data is needed. Solution: Allocate storage for data dynamically, as needed. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 13

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. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 14

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. planes = malloc(n * sizeof(flight)); We also need to change the type of the return value to the proper kind of pointer this is called casting. planes = (Flight*)malloc(n*sizeof(Flight)); University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 15

Example int airborneplanes; Flight *planes; printf( How many planes are in the air? ); scanf( %d, &airborneplanes); planes = (Flight*)malloc(sizeof(Flight) * airborneplanes); if (planes == NULL) { printf( Error in allocating the data array.\n );... } planes[0].altitude =... Note: Can use array notation or pointer notation. If allocation fails, malloc returns NULL. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 16

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. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 17

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 0 Node 1 Node 2 NULL University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 18

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 University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 19

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. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 20

Car data structure 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 cartype Car; struct cartype { int vehicleid; char make[20]; char model[20]; int year; int mileage; double cost; Car *next; /* ptr to next car in list */ } University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 21

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. Car *ScanList(Car *head, int searchid){ Car *previous, *current; previous = head; current = head->next; /* Traverse until ID >= searchid */ while ((current!=null) && (current->vehicleid < searchid)) { previous = current; current = current->next; } return previous; } University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 22

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: new node Node 0 Node 1 Node 2 NULL University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 23

Excerpts from Code to Add a Node newnode = (Car*) malloc(sizeof(car)); /* 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); } University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 24

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 0 Node 1 Node 2 NULL University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 25

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 ); } University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 26

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... University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell 27