390 likes | 623 Views
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.
E N D
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.
.name D a v i d \0 ? ? ? ? .age 22 .sex F 90.0 .grade_avg 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
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.
F i j i \0 ? ? ?……... 178 0 E 17 50 S variable resort Components of a structure .place typedef struct { int degrees, minutes; char direction; } long_lat_t; .longitude .latitude typedef struct { char place[20]; long_lat_t longitude, latitude; }location_t ; location_t resort; ReferenceData Type Value resort . latitude long_lat_t 17 50 ‘S’ resort . place ?? resort . longitude . direction ? ?
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 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 );
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); • }
893245521 593245422 693245521 493245926 393246525 883245521 3.98 2.71 3.41 3.91 2.71 3.71 Array of Structures stulist[0] . id Array stulist .id .gpa • #define MAX_STU 50 • typedef struct • { • int id; • double gpa; • } student_t; stulist[0] stulist[1] stulist[2] stulist[3] stulist[4] stulist[5]
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 • 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); P 32 bytes 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 • 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. Function data area ? nump ? letp ? ? studentp ? ?
Heap Function data area 26 nump p letp 23 studentp F 3.8 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; 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));
Heap 49.5 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. xp xcopyp
D C \0 12 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 \0 220 A C \0 115 current volts linkp
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.
volts linkp current n1_p ? n2_p ? D C \0 A C \0 12 115 n3_p 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 \0 A C \0 12 115 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.) volts linkp current n1_p n2_p ? n3_p
D C \0 A C \0 12 115 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 volts linkp current n1_p n2_p ? n3_p
n1_p List head : the first element in a linked list A C \0 220 A C \0 115 D C \0 12 current volts linkp Empty list=>a list of no node, represented in C by the pointer NULL, whose value is 0. 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;
A C \0 220 D C \0 D C \0 12 9 Advantages of Linked Lists • We can modify a link list easily. n1_p A C \0 115 current volts linkp 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.
A C \0 220 D C \0 D C \0 12 9 Advantages of Linked Lists • We can delete any node from a link list easily. n1_p current volts linkp A C \0 115 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.
n1_p A C \0 220 A C \0 115 current volts linkp D C \0 12 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);
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; • }
cur_nodep digit restp cur_nodep = cur_nodep->restp before 1 6 cur_nodep after 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”); • }
Recursive Function get_list • #incluse <stdio.h> // 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