1 / 62

Chapter 6 Structures

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

Download Presentation

Chapter 6 Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6 Structures By C. Shing ITEC Dept Radford University

  2. Objectives • Understand how to use structures • Understand how to call function by passing structures • Understand how to use unions

  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;

  4. Structure (Cont.) Example: struct student_record { char lastname[30]; char firstname[15]; float gpa; }; typedef struct student_record student_rec;

  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];…

  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;

  7. Read in Structure from Keyboard • Example: scanf(“%s%s%f”, student1.lastname, student1.firstname, &student1.gpa); // data: Doe John 2.0 Example1

  8. Structure Assignment • Assign field: student_any.lastname=student1.lastname; Example: Program, Data • Assign whole structure: Example: student_any= student1;

  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

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

  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

  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

  13. 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

  14. Sort Structures (Cont.) struct request { int number; double duration; }; typedef struct request requesttype; void input(requesttype request[], int *count);

  15. Sort Structures (Cont.) int main(void) { requesttype request[1000]; int count=0; … input(request, &count); sort_struct(request, count); }

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

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

  18. Sort Structures (Cont.) void swap (requesttype *s, requesttype *t) { requesttype tmp; tmp=*s; *s=*t; *t=tmp; }

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

  20. Sort Structures – Another Way (Cont.) void swapInt (requesttype *s, requesttype *t) { int tmp; tmp=s->number; s->number=t->number; t->number=tmp; }

  21. Sort Stuctures – Another Way (Cont.) void swapDouble (requesttype *s, requesttype *t) { double tmp; tmp=s->duration; s->duration=t->duration; t->duration=tmp; }

  22. Example Helpful Code Data Sort Student Name and Grades Structure; Program, Data

  23. Operators Priority

  24. Operators Priority (Cont.)

  25. Union • Create a new type (union union_name) by union sets of different data types • Declare as • union union_name { type1 variable1; …; };

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

  27. Example • Helpful Code

  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;

  29. 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;

  30. Structure with Bit Fields (Cont.) • Example: (Cont.) // assign 23 to snumber1 snumber1.int_sign=0; snumber1.i=23;

  31. Data Structure - stack • Stack: insert (push) and delete (pop) at the same place (top).

  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;

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

  34. Example 1– stack (Cont.) char top (const stack *stk) { return (stk->s[stk->top]); }; char pop (stack *stk) { return (stk->s[stk->top--]); }

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

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

  37. Example 2– stack (Cont.) void clear_stack(stack *stk) { stk->head=NULL; }

  38. 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 }

  39. Example 2– stack (Cont.) int top (const stack *stk) { return (stk->head->info); }

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

  41. Example 2– stack (Cont.) int isempty (stack *stk) { return (stk->head == NULL); }

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

  43. Example 2– stack (Cont.) Helpful Code Data

  44. Data Structure - Queue • Insert (enqueue) at the tail and Delete (dequeue) at the head.

  45. 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

  46. Example – Queue (Cont.) int isempty (node * head) { return (head == NULL); }

  47. 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");

  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

  49. 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; }

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

More Related