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
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Advertisements

Dynamic memory allocation
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.
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.
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.
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
Kernighan/Ritchie: Kelley/Pohl:
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:
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
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.
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.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
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.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
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.
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:
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
+ 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.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9-2 JSR Instruction Jumps to a location (like.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Declarations (aka prototype) int.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
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.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
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
Stack and Heap Memory Stack resident variables include:
5.13 Recursion Recursive functions Functions that call themselves
Chapter 19 Data Structures
Chapter 19 Data Structures
Chapter 19 Data Structures
Chapter 19 Data Structures
Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 16 Pointers and Arrays
Data Structures & Algorithms
C Structures and Memory Allocation
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Midterm 1 Review CS270 - Spring Semester 2019.
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. The only difference between struct and class is that we do not group functions, just data Example: We want to represent an airplane: 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.

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. typedef struct { 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 */ } FlightType; 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. (We do not have the separate vocabulary of “class” for the type definition and “object” for variable declaration / allocation.)‏

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. FlightType plane; 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[0] plane.flightNum[6] plane.altitude plane.longitude plane.latitude plane.heading plane.airspeed

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 short Boolean; typedef struct { 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]; FlightType 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.

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; FlightType plane; int y; 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 y plane.flightNum[0] plane.flightNum[6] plane.altitude plane.longitude plane.latitude plane.heading plane.airspeed x R5

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Array of Structs Can declare an array of structs: FlightType 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;

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: FlightType *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; This DOES NOT match the Java syntax because Java uses “.” syntax but matches the “->” situation.

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 Collide(Flight *planeA, Flight *planeB) { if (planeA->altitude == planeB->altitude) {... } else return 0; }

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 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.

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 Allocating Space for Variables Global data section All global variables stored here (actually all static variables)‏ R4 points to beginning Run-time stack Used for local variables R6 – TOP, R5, Frame Heap System calls keep track of memory instructions global data run-time stack 0x0000 0xFFFF PC R4 R6 R5 heap

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. 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));

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Example int airbornePlanes; FlightType *planes; printf(“How many planes are in the air?”); scanf(“%d”, &airbornePlanes); planes = (FlightType*) malloc(sizeof(FlightType) * airbornePlanes); if (planes == NULL) { printf(“Error in allocating the data array.\n”);... } planes[0].altitude =... If allocation fails, malloc returns NULL. 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 Car data structure Each car has the following characteristics: 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 */ }; Note that we were allowed to do the typedef before the struct definition!!!!

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Command Line Parameters An example of passing a file name to a program on the command line: > a.out myFile.txt Printing the file name: int main(int argc, char *argv[]) { printf(“You specified the file %s.\n”, argv[1]); …

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Using strings in C #include int strlen(char *); char *strcpy(char *dest, char *src); char *strncpy(char *dest, char *src, int maxlen); int strcmp(char *a, char *b); -1 if a before b in alphabetical order 0 if string a == string b 1 if a after b in alphabetical order char *strtok(char *a, char *tokens); Place a ‘\0’ at first occurrence of a token, return a char *strtok(NULL, char *tokens); Starting where it left off, divide at token, return next portion

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display int strlen(const char *s) Treated as an array: int strlen(char *s) { int length = 0; while (s[length] != ‘\0’) length++; return length; } Treated as a pointer: int strlen(char *s) { int length = 0; while (*(s++) != ‘\0’) length++; return length; }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Using strtok char s[30] = “Hello, how are you today?” char *p; p = strtok(s, “,?”); while (p) { printf(“%s\n”,p); p = strtok(NULL, “ “); } What will the output be?