User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { char name[10];

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
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.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Dynamic memory allocation in C and C++ 程式設計 潘仁義 CCU COMM.
Chapter 11 Structure and Union Types Instructor: Alkar / Demirer.
Topic 12 – Dynamic Memory Allocation & Linked Lists
User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { string name;
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.
Chapter 14 Dynamic Data Structures Instructor: Alkar & Demirer.
CS Data Structures Chapter 4 Lists.
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.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
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.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
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,
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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:
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Introduction to Data Structures Systems Programming Concepts.
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.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Chapter 11 Structure and Union Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
chap11 Chapter 11 Structure and Union Types.
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.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
Problem Solving and Program Design in C Chap. 11 Structure and Union Types Chow-Sing Lin.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
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.
© 2012 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Programming application CC213 Week 08 – Struct & Unions– Chapter 10.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
Stack and Heap Memory Stack resident variables include:
Dynamic Allocation Review Structure and list processing
5.13 Recursion Recursive functions Functions that call themselves
Lectures linked lists Chapter 6 of textbook
Data Structure and Algorithms
CSCI206 - Computer Organization & Programming
CSCE 210 Data Structures and Algorithms
Dynamic memory allocation in C and C++
Introduction to Linked Lists
Linked List.
Structure and Union Types
Dynamic memory allocation in C and C++
Dynamic memory allocation in C and C++
Chapter 11 Structure and Union Types.
Dynamic Data Structures
Presentation transcript:

User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { char name[10]; int age; char sex; double grade_avg; } student_t; typedef statement itself allocates no memory. A variable declaration is required to allocate storage space for a structured data object. E.g. student_t one_student; This type definition is a template that describes the format of a student structure and the name and type of each component.

How to reference a member of a Structure We can reference a component of a structure by using the direct component selection operator, which is a period. one_student. name one_student. age one_student. sex one_student. grade_avg A name chosen for a component of one structure may be the same as the name of a component of another structure.

Assigning Values to Components of variable one_student strcpy(one_student. name, “David”); one_student. age = 22; one_student. sex = ‘F’; one_student. grade_avg = 90.0; variable one_student, a structure of type student_t D a v i d \0 ? ? ? ? 22 F 90.0.name.age.sex.grade_avg

Hierarchical Structure Hierarchical structure => a structure containing components that are structures (arrays or structs). typedef struct { char name[10]; int age; char sex; double grade_avg; } student_t; Note: To avoid confusion, we choose user_defined type names that use lowercase letters and end in the suffix_t.

Components of a structure typedef struct { char place[20]; long_lat_t longitude, latitude; }location_t ; location_t resort; typedef struct { int degrees, minutes; char direction; } long_lat_t; F i j i \0 ? ? ?…… S E variable resort Reference Data Type Value resort. latitude long_lat_t ‘S’ resort. place ? ? resort. longitude. direction ? ?.place.longitude.latitude

Manipulating Whole Structure The name of a structure type variable used with no component selection operator refers to the entire structure. A new copy of a structure’s value can be made by simply assigning one structure to another. Example: Student_t student_one, student_two; student_one = student_two;

Structure Type Data as Input Parameter void print_student(student_t stu) { printf(“Name : %s\n”, stu. name); printf(“Age: %d\n”, stu. age); printf(“Sex: %c\n”, stu. sex); printf(“Grade Avg: %f\n”, stu. grade_avg); } Call statement: print_student( one_student ); Input parameter

Function Comparing Two Structured Values for Equality int student_equal (student_t stu_1, // takes two students student_t stu_2) // as input argument { return ( strcmp(stu_1.name, stu_2.name) == 0 && stu_1. age == stu_2. age && stu_1. sex == stu_2. sex && stu_1. grade_avg == stu_2. grade_avg); } // returns 1 if all components match, otherwise returns 0.

Function with a Structured Output Argument int scan_student (student_t *stup) // output - address of student_t { int result; result = scanf(“%s%d%c%lf”, (*stup). name, & (*stup). age, &(*stup). sex, &(*stup). grade_avg); if (result == 5) result = 1; else if (result != EOF) result = 0; return (result); } 1 => successful 0 => error EOF => insufficient data before end of file

Indirect Component Selection Operator int scan_student (student_t *stup) // output - address of student_t { int result; result = scanf(“%s%d%c%lf”, stup -> name, &stup -> age, &stup -> sex, &stup -> grade_avg); if (result == 5) result = 1; else if (result != EOF) result = 0; return (result); } 1 => successful 0 => error EOF => insufficient data before end of file

Function that Returns a Structured Result Type student_t get_student (void) { student_t stu; scanf(“%s%d%c%lf”, stu. name, &stu. age, &stu. sex, &stu. grade_avg); return (stu); }

Array of Structures #define MAX_STU 50 typedef struct { int id; double gpa; } student_t; Array stulist stulist[0] stulist[1] stulist[2] stulist[3] stulist[4] stulist[5] stulist[0]. id.id.gpa

Union Types typedef union { int wears_wig; // if the person is bald, we will // notice if he wears a wig char color[20]; // if the person has hair, we will // record hair color } hair_t; hair_t hair_data; // creates a variable built on the // template of the type definition hair_data does not contain both wears_wig and color. It has either wear_wig or color. The amount of memory is determined by the largest component of the union.

Union Type typedef struct { int bald; // component that indicates which // interpretation of union is correct at present hair_t h; } hair_info_t; If the person is bald, the wear_wig interpretation of component h is valid. For nonbald person, the color interpretation is valid and represents the color of the person’s hair.

Function that Display a Structure with Union Type Component void print_hair_info(hair_info_t hair) { if (hair.bald) { printf(“Subject is bald”); if (hair.h.wears_wig) printf(“, but wears a wig.\n”); else printf(“and does not wear a wig.\n”); } else printf(“Subject’s hair color is %s.\n”, hair.h.color); }

Union A union is a derived data type- like a structure- whose members share the same storage space. For different situations in a program, some variables may not be relevant, but other variables are relevant. So a union shares the space instead of wasting storage on variables that are not being used. The members of a union can be of any type. The number of bytes used to store a union must be at least enough to hold the largest member. In most cases, unions contain two or more data types. Only one member, and thus one data type, can be referenced at a time. It is the programmer’s responsibility to ensure that the data in a union is referenced with the proper data type.

Dynamic Data Structure and Link Lists

Dynamic Data Structure Dynamic data structure => structures that expand and contract as a program executes. This structures allow programmers to take decision later on space in processing a data set. This increases program’s flexibility. In case of array, we have to determine the maximum list size before compilation. One dynamic memory allocation function allows us to delay the setting of the maximum list size until the program is already running. Another function permits us to allocate space separately for each list member. So the program itself never actually sets an upper bound on the list size.

Dynamic Memory Allocation To allocate an integer variable, a character variable, and a structured variable dynamically, we call the C memory allocation function malloc. malloc resides in the stdlib library. malloc requires a single argument - a number indicating the amount of memory space needed. Use sizeof operator to the data type: malloc(sizeof(int)) allocates exactly enough space to hold one type int value and returns a pointer to (the address of) the block allocated.

Dynamic Memory Allocation malloc(size_in_bytes) is a request to the OS to create a new structure of specified size and returns a pointer to the structure. P = malloc(32); 32 bytes P A chunk of memory is given by the OS from the heap.

malloc In C, a pointer is always point to some specific type. Therefore, the data type of the value returned by malloc should always be cast to the specific type we need. int *nump; char *letp; student_t *studentp; nump = (int *)malloc(sizeof (int)); letp = (char *)malloc(sizeof (char)); studentp = (student_t *)malloc(sizeof(student_t));

Heap Heap => region of memory in which function malloc dynamically allocates blocks of storage. Heap is separate from stack. Stack is the region of memory in which function data areas are allocated and reclaimed as functions are entered and exited. Heap Function data area studentp letp nump ? ? ? ? ? ?

How Values are Stored in Memory Values can be stored in the newly allocated memory using the indirection operator(*). *nump = 26; student_t stu_one *letp = ‘p’; = {“John”, 23, ‘F’, 3.8}; *studentp = stu_one; Heap Function data area studentp letp nump 26 p 23 F 3.8 J o h n \o

How to Access Components of a Dynamically allocated Structure Components of a structure can be referenced using a combination of the indirection (*) and direct component selection (.) operators. Example: (*studentp).name or studentp ->name -> is a minus sign followed buy a greater-than symbol. Either notation can be used to access a component of a dynamically allocated structure. In general, (*structp).component or struct ->component

Dynamic Array Allocation with calloc We use function malloc to allocate a single memory block of any built-in or user-defined type. We use the contiguous allocation function calloc to dynamically create an array of elements of any built-in or user-defined type. calloc also resides in stdlib library. calloc takes two arguments: - the number of array elements needed and - the size of one element. Example: int *array_of_nums; array_of_nums = (int *)calloc(num_nums, sizeof(int));

Returning Memory Cells to the Heap Function free is used to return memory cells to the heap so that they can be reused later in response to calls to calloc and malloc. Example1: free(letp); returns to the heap the cell whose address is in letp. Example 2: make sure you have no further need for a particular memory block before you free it. double *xp, xcopyp; xp (double *)malloc(sizeof(double)); *xp = 49.5; xcopy = xp; free(xp); If we use xcopyp after it is freed, errors can results Heap xp xcopyp

Linked List A link list is a sequence of nodes where each node is linked, or connected, to the node following it. Link lists are like chains of children’s “pop beads”, where each bead has a hole at one end and a plug at the other. We can connect the beads to form a chain and we can add, remove, and modify. A link list of three nodes: A C \0115 A C \0220 D C \012 currentvoltslinkp

Structures with Pointer Components To construct a dynamic linked list, we need nodes that have pointer components. We may not know in advance the size of the lists. We can allocate storage for each node as needed and use its pointer component to connect to the next node. A definition of a type appropriate for a node of the link list typedef struct node_s { char current[3]; int volts; struct node_s *linkp; } node_t; struct node_s is an alternate name for type node_t We use struct node_s * rather than node_t * because the compiler has not yet seen the name node_t.

Allocation & Initialization of the Data Components of Nodes node_t *n1_p, *n2_p, *n3_p; n1_p = (node_t *) malloc (sizeof (node_t)); strcpy(n1_p->current, “AC”); n1_p->volts = 115; n2_p = (node_t *) malloc (sizeof (node_t)); strcpy(n2_p->current, “DC”); n2_p->volts = 12; n3_p = n2_p; D C \012 A C \0115 ? ? n1_p n2_p n3_p current voltslinkp

Connecting Nodes The pointer assignment statement n1_p ->linkp = n2_p; copies the address stored in n2_p into the linkp component of the node accessed through n1_p ( first node in fig.) D C \012 A C \0115 ? n1_p n2_p n3_p current voltslinkp

How to access the 12 in volts? We have three ways to access 12 in the volts component of the second node: n2_p ->volts n3_p->volts n1_p->linkp->volts D C \012 A C \0115 ? n1_p n2_p n3_p current voltslinkp

Linked List node_t *n1_p; n1_p = (node_t *) malloc (sizeof (node_t)); strcpy(n1_p->current, “AC”); n1_p->volts = 115; n1_p->linkp = (node_t *) malloc (sizeof (node_t)); strcpy(n1_p->linkp->current, “DC”); n1_p->linkp->volts = 12; n1_p->linkp->linkp = (node_t *) malloc (sizeof (node_t)); strcpy(n1_p->linkp->linkp->current, “AC”); n1_p->linkp->linkp->volts = 220; n1_p->linkp->linkp->linp = NULL; Empty list=>a list of no node, represented in C by the pointer NULL, whose value is 0. A C \0115 A C \0220 D C \012 currentvoltslinkp n1_p List head : the first element in a linked list

Advantages of Linked Lists We can modify a link list easily. A C \0115 D C \012 A C \0220 currentvoltslinkp n1_p D C \09 A new node containing DC 9 is inserted between the nodes DC 12 and AC 220 by changing only one pointer value(the one from DC 12) and setting the pointer from the new node to point to AC 220.

Advantages of Linked Lists We can delete any node from a link list easily. A C \0115 D C \012 A C \0220 currentvoltslinkp n1_p D C \09 The second node containing DC 12 is deleted by changing the pointer from the node AC 115. The deleted node is effectively disconnected from the list. The new list consists of AC 115, DC 9, and AC 220.

What is displayed by the Code Fragment ? n2_p = n1_p->linkp->linkp; printf(“ %s %s %s\n”, n2_p->current, n1_p->linkp>current, n1_p->current); printf(“%3d%4d$4d\n”, n1_p->linkp->volts, n1_p->volts, n2_p->volts); A C \0115 A C \0220 D C \012 currentvoltslinkp n1_p

Traversing a List: Recursive version Traversing a list means to process each node in the list in sequence. To traverse a list, we must start at the list head and follow the list pointers. To display the contents of a list, we traverse the list and display only the values of the information components, not the pointer fields. void printf_list(list_node_t *headp) { if (headp == NULL) // simple case- an empty list printf(“\n”); else // recursive step, handles first element { // leaves rest to recursion printf(“%d”, headp->digit); typedef struct list_node_s{ int digit; print_list(headp->restp); struct list_node_s * restp; } }list_node_t; }

Iterative Version of print_list Void print_list(list_node_t *headp) { list_node_t *cur_nodep; for (cur_nodep = headp; // start at beginning cur_nodep != NULL; // not at end yet cur_nodep = cur_nodrp->restp) printf(“%d”, cur_nodep->digit); printf(“\n”); } digitrestpcur_nodep 1 6 before cur_nodep after cur_nodep = cur_nodep->restp

Recursive Function get_list #incluse // Function get_list creates a linked list from a sequence of #define SENT -1 // integers entered as input. Sentinel -1 marks the end of data list_node_t *get_list(void) { int data; list_node_t *ansp; scanf(“%d”, &data); if (data == SENT) // algorithm recognizes the sentinel value as an empty ansp = NULL; // data list and returns NULL. else // function views a nonsentinel data item as the first value in the list it is // creating. So it allocates a node and places the integer in the digit comp. { ansp = (list_node_t *)malloc (sizeof(list_node_t)); ansp->digit; ansp-.restp = get_list(); } return (ansp); }

Searching a List for a Target // Searches a list for a target value. Returns a pointer to the first // node containing target if found, otherwise returns NULL. list_node_t *search(list_node_t *headp, int target) { list_node_t *cur_nodep; for (cur_nodep = headp; cur_nodep != NULL && cur_nodep->digit != target; cur_nodep = cur_nodep->restp) { } return (cur_nodep); } Note: Order of the tests in the loop is critical.If the order of the loop is reversed, our program will attempt to follow the NULL pointer and cause run-time error. cur_nodep->digit != target && cur_nodep != NULL C does short-circuit evaluation