chapter 6 structures
DESCRIPTION
Chapter 6 Structures. By C. Shing ITEC Dept Radford University. Objectives. Understand how to use structures Understand how to call function by passing structures Understand how to use unions. Structure. A record that can store different data types - PowerPoint PPT PresentationTRANSCRIPT
Chapter 6 Structures
By C. Shing
ITEC Dept
Radford University
Slide 2
Objectives Understand how to use structures Understand how to call function by passing
structures Understand how to use unions
Slide 3
Structure A record that can store different data types Declared data type (struct structure_name) first as
struct [structure_name] {type1 fieldname1;… } [variable_lists];
Then define a new type by typedef struct structure_name structure_type;or typedef struct {
type1 fieldname1;… } structure_type;
Slide 4
Structure (Cont.)
Example:
struct student_record {
char lastname[30];
char firstname[15];
float gpa; };
typedef struct student_record student_rec;
Slide 5
Structure (Cont.) Declared variables then as
struct structure_name variable_list; Or use
structure_type variable_list;
Example:
struct student_record student1, student2;
struct student_record student[100];
or
student_rec student[100];…
Slide 6
Initialize Structure Similar to initialize an array Fill in 0 or NULL if not enough data
Example:
student_rec student1={“Doe”, “John”, 2.0};
student_rec student_any;
Slide 7
Read in Structure from Keyboard Example:
scanf(“%s%s%f”, student1.lastname,
student1.firstname, &student1.gpa);
// data: Doe John 2.0
Example1
Slide 8
Structure Assignment Assign field:
student_any.lastname=student1.lastname;
Example: Program, Data Assign whole structure:
Example:
student_any= student1;
Slide 9
Pointer and Structure If a pointer p to a stucture_type variable, then
to access a field (or member), use p -> fieldname
Or (*p).fieldname
Example 2
Slide 10
Pointer and Structure (Cont.)Example:
student_rec student1={“Doe”, “John”, 2.0},*student_pointer=&student1;
Then student_pointer->lastname = “Doe”; (*student_pointer).firstname = “John”; student_pointer->gpa=2.0; (student_pointer->firstname)[3]=‘n’; (*(student_pointer->firstname))+2=‘L’;
Slide 11
Pass Structure to Function Use pass-by-value: pass a copy of structure,
Default, not efficient If structure is changed after function call, must return the structure_type result The returned result must be assigned back to the original variable
Example: student1=change_gpa (student1);
student_rec change_gpa (student_rec student_any) { printf(“Please enter new gpa:\n”); scanf(“%f”, &student_any.gpa); return student_any; }
Example 3
Slide 12
Pass Structure to Function (Cont.) Use pass-by-reference: pass in pointer,
very efficient
Example: change_gpa (&student1);
void change_gpa (student_rec *student_pointer) { printf(“Please enter new gpa:\n”); scanf(“%f”, &student_pointer->gpa); }
Example 4
Slide 13
Sort Structures Problem: input data into array of structures And then sort themData:1 15.0 2 15.03 11.04 9.05 9.0
Slide 14
Sort Structures (Cont.)struct request {
int number;double duration;
};
typedef struct request requesttype;
void input(requesttype request[], int *count);
Slide 15
Sort Structures (Cont.)
int main(void)
{
requesttype request[1000];
int count=0;…
input(request, &count);
sort_struct(request, count);
}
Slide 16
Sort Structures (Cont.)void input(requesttype request[], int *count){
int i;
for (i=0; scanf("%d", &request[i].number), request[i].number !=0;
i++){
scanf("%lf", &request[i]. duration);…
(*count)++;}
}
Slide 17
Sort Structures (Cont.)void sort_struct (requesttype w[], int n){
int i, j;for (i=0; i<n; ++i)
for (j=i+1; j<n;++j)if (w[i].duration > w[j].duration)
swap (&w[i], &w[j]);}
Slide 18
Sort Structures (Cont.)
void swap (requesttype *s, requesttype *t)
{
requesttype tmp;
tmp=*s;
*s=*t;
*t=tmp;
}
Slide 19
Sort Structures – Another Way (Cont.)void sort_struct (requesttype w[], int n){
int i, j;for (i=0; i<n; ++i)
for (j=i+1; j<n;++j)if (w[i].duration > w[j].duration){
swapInt (&w[i], &w[j]);swapDouble (&w[i], &w[j]);
}}
Slide 20
Sort Structures – Another Way (Cont.)
void swapInt (requesttype *s, requesttype *t)
{
int tmp;
tmp=s->number;
s->number=t->number;
t->number=tmp;
}
Slide 21
Sort Stuctures – Another Way (Cont.)
void swapDouble (requesttype *s, requesttype *t)
{
double tmp;
tmp=s->duration;
s->duration=t->duration;
t->duration=tmp;
}
Slide 22
Example
Helpful Code
Data
Sort Student Name and Grades Structure;
Program, Data
Slide 23
Operators Priority
Operator Same Priority Rule
(),postfix++/--,[],.,-> Left to right
Unary +/-, prefix++/--, !, ~,&, * Right to left
*, /, % Left to right
+, - Left to right
<<, >> Left to right
<, >, <=, >= Left to right
==, != Left to right
Slide 24
Operators Priority (Cont.)
Operator Same Priority Rule
&
^
|
&& Left to right
|| Left to right
?: Right to left
, Left to right
Slide 25
Union Create a new type (union union_name)
by union sets of different data types Declare as
union union_name {
type1 variable1;
…; };
Slide 26
Union (Cont.) Example:
union number { long i; float f;};
typedef union number number; number number1, number2; number1.i=100; number2.f=-1.23; printf(“%d%f\n”, number1.i, number1.f); printf(“%d%f\n”, number2.i, number2.f);
Slide 27
Example Helpful Code
Slide 28
Structure with Bit Fields Purpose: reduce space Declare structure data types using bits fields as
struct structure_name {unsigned field1: number of bits,
field2: number of bits, :0, // align to next word …; };
typedef struct structure_name structure_type;structure_type variable_list;
Slide 29
Structure with Bit Fields (Cont.) Example: Create a small_number that has 7 bits
of signed integer or floatstruct small_number {unsigned int_sign: 1, // 0: positive, 1: negative using 2s complement
i : 6, :0, // align to next word float_sign: 1, f : 6; // don’t worry align at the end};
typedef struct small_number small_number;small_number s_number1;
Slide 30
Structure with Bit Fields (Cont.) Example: (Cont.)
// assign 23 to snumber1
snumber1.int_sign=0;
snumber1.i=23;
Slide 31
Data Structure - stack Stack: insert (push) and delete (pop)
at the same place (top).
Slide 32
Example 1- stack Write a program that implements a stack of
characters using an array.
typedef struct stack {
char s[STACKSIZE];
int top;
} stack;
Slide 33
Example 1– stack (Cont.)void clear_stack (stack *stk) { stk->top=-1;};
void push(char c, stack *stk) { stk->top++; stk->s[stk->top]=c;}
Slide 34
Example 1– stack (Cont.)
char top (const stack *stk) {
return (stk->s[stk->top]);
};
char pop (stack *stk) {
return (stk->s[stk->top--]);
}
Slide 35
Example 1– stack (Cont.)
int is_full (const stack *stk) {
return ((int) (stk->top == STACKSIZE-1));
};
int is_empty (const stack *stk) {
return ((int) (stk->top == -1));
};
Slide 36
Example 2- stack Write a program that implements a stack of
integers using a linked list.typedef struct node {
int info;struct node *next;
} node;
typedef struct stack {node * head;
} stack;;
Slide 37
Example 2– stack (Cont.)
void clear_stack(stack *stk)
{
stk->head=NULL;
}
Slide 38
Example 2– stack (Cont.)// insert item to head, delete from headvoid push (int item, stack *stk) {
node *newnode;
newnode = malloc(sizeof(node)); // dynamically create a new nodeif (!newnode)
printf("No memory is available.\n");else{
newnode->info= item;newnode->next= stk->head;
stk->head=newnode;} // else
}
Slide 39
Example 2– stack (Cont.)
int top (const stack *stk)
{
return (stk->head->info);
}
Slide 40
Example 2– stack (Cont.)int pop (stack *stk){
int item;node *deletednode;
deletednode=stk->head;item=deletednode->info;stk->head=deletednode->next;free(deletednode);
return item;}
Slide 41
Example 2– stack (Cont.)
int isempty (stack *stk)
{
return (stk->head == NULL);
}
Slide 42
Example 2– stack (Cont.)void output (stack stk){
printf ("--------------------------”);Printf(“All items in the stack:-------------------------\n");for (;!isempty(&stk);) {
printf("%d\n", top(&stk));stk.head=(stk.head)->next;
}}
Slide 43
Example 2– stack (Cont.)
Helpful Code
Data
Slide 44
Data Structure - Queue Insert (enqueue) at the tail and
Delete (dequeue) at the head.
Slide 45
Example - Queue Write a program that implements a queue of
integers using a linked list.struct node {
int info;struct node *next;
};typedef struct node node;node *head=NULL, *tail=NULL; // initialize
Slide 46
Example – Queue (Cont.)
int isempty (node * head)
{
return (head == NULL);
}
Slide 47
Example – Queue (Cont.)// insert item to tail, delete from headvoid enqueue (node **ptrhead,
node **ptrtail, int item){
node *newnode;
// dynamically create a new nodenewnode = malloc(sizeof(node)); if (!newnode)
printf("No memory is available.\n");
Slide 48
Example – Queue (Cont.)// insert item to tail, delete from head (Cont.)else{
newnode->info= item;newnode->next=NULL;
if (isempty(*ptrhead)) // if (!(*ptrhead)) means head is equal to NULL*ptrhead=newnode;
else(*ptrtail)->next=newnode;
*ptrtail=newnode;} // else
} // enqueue
Slide 49
Example – Queue (Cont.)// delete from head and return infoint dequeue (node **ptrhead, node **ptrtail){
int item;node *deletednode;
deletednode=*ptrhead;item=deletednode->info;*ptrhead=deletednode->next;if (isempty(*ptrhead))
*ptrtail=NULL;free(deletednode);
return item;}
Slide 50
Example – Queue (Cont.)void output (node *head){
printf ("--------------------------”); printf(“All items in the queue:-------------------------\
n");for (;!isempty(head);) // for (;head != NULL;) {
printf("%d\n", head->info);head=head->next;
}}
Slide 51
Example – Queue (Cont.)
Program (node is int) Code
Data
Program (node is a structure) Code
Data
Slide 52
Data Structure – Binary Tree Each (parent) node has at most 2 children Binary search tree:
right child node value > parent node value > left
child value
Slide 53
Example – Binary search tree Write a program that implements a
binary search tree of integers using a linked list.
typedef struct node {
struct node *left;
int info;
struct node *right;
} node;
Slide 54
Example – Binary search tree (Cont.)
typedef struct tree {
node * root;
} tree;
Slide 55
Example – Binary search tree (Cont.)
void clear_tree(tree *bst)
{
bst->root=NULL;
}
Slide 56
Example – Binary search tree (Cont.)void insert (int item, tree *bst) {
node *newnode;
if (bst->root == NULL) // base case{
newnode = malloc(sizeof(node)); // dynamically create a new nodeif (newnode == NULL)
printf("No memory is available.\n");else{
newnode->info= item;newnode->left= NULL;newnode->right= NULL;bst->root=newnode;printf("%d\n", bst->root->info);
}}
Slide 57
Example – Binary search tree (Cont.)
Else // inductive case{
if (item> bst->root->info)bst->root=bst->root->right;
elsebst->root=bst->root->left;
insert(item, bst);}} // insert
Slide 58
Example – Binary search tree (Cont.)
Helpful Code
Data
Slide 59
PracticeGiven struct student {
char lastname[15]; long studentid; char grade;
}; struct student tmp, *p=&tmp; tmp.grade='A'; tmp.lastname="Casanova"; tmp.studentid=910017;
Slide 60
Practice (Cont.)Find the values of the following table: Expression Value ________ _____ tmp.grade tmp.lastname (*p).studentid *p->lastname+1 *(p->lastname+2)
Slide 61
Practice (Cont.)Find the values of the following table: Expression Value ________ _____ tmp.grade ‘A’tmp.lastname “Casanova”(*p).studentid 910017*p->lastname+1 ‘D’*(p->lastname+2) ‘s’
Slide 62
References Deitel & Deitel: C How to Program, 4th ed.,
Chapter 10 & 12, Prentice Hall