Top Banner
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.
39

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

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { char name[10];

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.

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

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.

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

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 ? ? ? ?22F

90.0

.name

.age

.sex

.grade_avg

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

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.

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

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 ? ? ?……...178

S500

17E

variable resort

Reference Data Type Valueresort . latitude long_lat_t 17 50 ‘S’resort . place ? ?resort . longitude . direction ? ?

.place.longitude.latitude

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

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;

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

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

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

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.

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

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 => successful0 => errorEOF => insufficient data before end of file

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

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 => successful0 => errorEOF => insufficient data before end of file

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

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

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

Array of Structures

#define MAX_STU 50

typedef struct

{

int id;

double gpa;

} student_t;

893245521 3.71

593245422 2.71

693245521 3.98

493245926 3.41

393246525 2.71

883245521 3.91

Array stulist

stulist[0]

stulist[1]

stulist[2]

stulist[3]

stulist[4]

stulist[5]

stulist[0] . id

.id .gpa

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

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.

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

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.

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

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

}

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

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.

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

Dynamic Data Structure and Link Lists

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

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.

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

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.

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

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.

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

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

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

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.

HeapFunction data area

studentp

letp

nump?

?

????

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

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;

HeapFunction data area

studentp

letp

nump26

p

23F3.8

J o h n \o

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

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

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

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

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

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.

49.5Heap

xp

xcopyp

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

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 115 A C \0 220 D C \0 12

current volts linkp

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

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.

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

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 12

A C \0 115 ?

?

n1_p

n2_p

n3_p

current volts linkp

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

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 \0 12

A C \0 115

?

n1_p

n2_p

n3_p

current volts linkp

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

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 \0 12

A C \0 115

?

n1_p

n2_p

n3_p

current volts linkp

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

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 nonode, represented in C by the pointer NULL, whose value is 0.

A C \0 115 A C \0 220 D C \0 12

current volts linkp

n1_p List head : the first element in a linked list

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

Advantages of Linked Lists• We can modify a link list easily.

A C \0 115 D C \0 12

A C \0 220

current volts linkp

n1_p

D C \0 9

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.

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

Advantages of Linked Lists• We can delete any node from a link list easily.

A C \0 115 D C \0 12

A C \0 220

current volts linkp

n1_p

D C \0 9

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.

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

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 \0 115 A C \0 220 D C \0 12

current volts linkp

n1_p

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

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;

}

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

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

}

digit restpcur_nodep

1 6before

cur_nodepafter

cur_nodep= cur_nodep->restp

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

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

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

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 programwill attempt to follow the NULL pointer and cause run-time error.

cur_nodep->digit != target && cur_nodep != NULLC does short-circuit evaluation