630 likes | 780 Views
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
E N D
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 • 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;
Structure (Cont.) Example: struct student_record { char lastname[30]; char firstname[15]; float gpa; }; typedef struct student_record student_rec;
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];…
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;
Read in Structure from Keyboard • Example: scanf(“%s%s%f”, student1.lastname, student1.firstname, &student1.gpa); // data: Doe John 2.0 Example1
Structure Assignment • Assign field: student_any.lastname=student1.lastname; Example: Program, Data • Assign whole structure: Example: student_any= student1;
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
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’;
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
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
Sort Structures • Problem: input data into array of structures And then sort them Data: 1 15.0 2 15.0 3 11.0 4 9.0 5 9.0
Sort Structures (Cont.) struct request { int number; double duration; }; typedef struct request requesttype; void input(requesttype request[], int *count);
Sort Structures (Cont.) int main(void) { requesttype request[1000]; int count=0; … input(request, &count); sort_struct(request, count); }
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)++; } }
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]); }
Sort Structures (Cont.) void swap (requesttype *s, requesttype *t) { requesttype tmp; tmp=*s; *s=*t; *t=tmp; }
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]); } }
Sort Structures – Another Way (Cont.) void swapInt (requesttype *s, requesttype *t) { int tmp; tmp=s->number; s->number=t->number; t->number=tmp; }
Sort Stuctures – Another Way (Cont.) void swapDouble (requesttype *s, requesttype *t) { double tmp; tmp=s->duration; s->duration=t->duration; t->duration=tmp; }
Example Helpful Code Data Sort Student Name and Grades Structure; Program, Data
Union • Create a new type (union union_name) by union sets of different data types • Declare as • union union_name { type1 variable1; …; };
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);
Example • Helpful Code
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;
Structure with Bit Fields (Cont.) • Example: Create a small_number that has 7 bits of signed integer or float struct 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;
Structure with Bit Fields (Cont.) • Example: (Cont.) // assign 23 to snumber1 snumber1.int_sign=0; snumber1.i=23;
Data Structure - stack • Stack: insert (push) and delete (pop) at the same place (top).
Example 1- stack • Write a program that implements a stack of characters using an array. typedef struct stack { char s[STACKSIZE]; int top; } stack;
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; }
Example 1– stack (Cont.) char top (const stack *stk) { return (stk->s[stk->top]); }; char pop (stack *stk) { return (stk->s[stk->top--]); }
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)); };
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;;
Example 2– stack (Cont.) void clear_stack(stack *stk) { stk->head=NULL; }
Example 2– stack (Cont.) // insert item to head, delete from head void push (int item, stack *stk) { node *newnode; newnode = malloc(sizeof(node)); // dynamically create a new node if (!newnode) printf("No memory is available.\n"); else { newnode->info= item; newnode->next= stk->head; stk->head=newnode; } // else }
Example 2– stack (Cont.) int top (const stack *stk) { return (stk->head->info); }
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; }
Example 2– stack (Cont.) int isempty (stack *stk) { return (stk->head == NULL); }
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; } }
Example 2– stack (Cont.) Helpful Code Data
Data Structure - Queue • Insert (enqueue) at the tail and Delete (dequeue) at the head.
Example - Queue • Write a program that implements a queue of integers using a linked list. struct node { int info; struct node *next; }; typedefstruct node node; node *head=NULL, *tail=NULL; // initialize
Example – Queue (Cont.) int isempty (node * head) { return (head == NULL); }
Example – Queue (Cont.) // insert item to tail, delete from head void enqueue (node **ptrhead, node **ptrtail, int item) { node *newnode; // dynamically create a new node newnode = malloc(sizeof(node)); if (!newnode) printf("No memory is available.\n");
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
Example – Queue (Cont.) // delete from head and return info int 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; }
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; } }