Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exercise 11 Dynamic allocation, structures, linked lists.

Similar presentations


Presentation on theme: "Exercise 11 Dynamic allocation, structures, linked lists."— Presentation transcript:

1 Exercise 11 Dynamic allocation, structures, linked lists

2 Where to get these slides: http://www.cs.tau.ac.il/~sorkine/courses/cprog06/ Go to the very bottom of the page (where it says “Liam’s class”)

3 Dynamic allocation example Implement the function my_strcat :  Input – two strings, s1 and s2  Output – a pointer to a dynamically allocated concatenation (‘shirshur’)  For example: The concatenation of “hello_” and “world!” is the string “hello_world!”

4 Solution my_strcat.c (my_strcat2.c)

5 What’s wrong with this? char *my_strcat(char *str1, char *str2) { int len; char result[500]; /* Let’s assume this is large enough */ len = strlen(str1); strcpy(result, str1); strcpy(result+len, str2); return result; }

6 Structures Often we want to be able to manipulate ‘logical entities’ as a whole  For example, complex numbers, dates, student records, etc’  Each of these must be composed of more than one variable, but are logically units

7 Structures A struct (short for structure) is a collection of variables of different types, gathered into one super-variable It is used to define more complex data types Variables in a struct are called members or fields

8 Example – complex numbers. The following is the definition of a new ‘variable’ of type complex number: struct complex { int real; int img; }; Once we define a structure, we can treat it as any type.  In a program, we can then write: struct complex num1, num2, num3;

9 Access structure members If A is a variable of some structure type with a member named x, then A.x is that member of A  struct complex C; C.real = 0; If pA is a pointer to a structure with a member x, then pA->x is that member of the variable pointed by pA.  This is simply shorthand for (*pA).x struct complex *pc = &C; pc->real = 1;

10 A more convenient usage with typedef An alternative definition: typedef struct complex_t { int real; int img; } complex; Now the program has a new variable type - “ complex ”. This way we don’t have to write “ struct complex ” every time! For example, we can define two complex numbers in the following line: complex num1, num2;

11 Exercise Write a struct that represents a date (day, month year) Write a function that increments the date: void IncDate(Date * d); For example, 31.1.2006  1.2.2006 Solution: IncDate.c

12 Miscellaneous structure trivia Structure members may be ordinary variable types, but also other structures and even arrays! Structures can therefore be rather large and take up a lot of space Many times we prefer to pass structures to functions by address, and not by value  Thus a new copy of the structure is not created – just a pointer to the existing structure

13 More trivia Structures cannot be compared using the == operator  They must be compared member by member  Usually this will be done in a separate function Structures can be copied using the = operator  Member-wise copy

14 Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure that contains a member which is an array, the array is copied element by element  Not just the address gets copied  For example - array_member.c Reminder – ordinary arrays can’t be copied simply by using the ‘=‘ operator  They must be copied using a loop

15 Structures containing arrays When passing the structure to a function by value  Changing the array field inside the function won’t change it in the calling function Reminder – when passing an ordinary array to a function, all that gets passed is the address of its first element  Hence every change to the array within the function, changes the array in the calling function

16 Pointers are another matter If the member is a pointer, for example to a dynamically allocated array, all that gets copied is the pointer (the address) itself  For example, pointer_member.c Hence, we should take extra care when manipulating structures that contain pointers

17 Implementing a student package We want to create (part of) a course- management program. We need to:  Maintain a list of the participating students  Keep track of their final grade  Be able to add and remove students from the course  And so on…

18 Storing a list of students One way to go would be by using an array of student structures (or pointers to structures). There are problems with this –  we must allocate a big-enough array before accepting students (how do we know what’s big enough?)  How shall we remove students from the list without creating “holes”?  How can we maintain the list sorted by grade?  Insertion and deletion may be problematic

19 Linking students A better alternative might be using a linked list, by “self reference”. typedef struct Student_t { char ID[ID_LENGTH]; char Name[NAME_LENGTH]; int grade; struct Student_t *next; /* A pointer to the next item on the list */ } Student;

20 Linked lists - searching … Head ?? ! * A list is always maintained by its head (why is this enough?)

21 Linked lists - insertion … Head Insert new item: PreviousNext

22 Linked lists - deletion … Head PreviousCurrent

23 Creating a new kind of student Usually when using linked lists we don’t know how many elements will be in the list Therefore we would like to be able to dynamically allocate new elements when the need arises A possible implementation follows…

24 Creating a new student Student * create_student(char name[], char ID[], int grade) { Student *std; std = (Student *)malloc(sizeof(Student)); if (std == NULL) { printf(“Memory allocation error!\n”); exit(1); } strcpy(std->Name, name); strcpy(std->ID, ID); std->grade = grade; std->next = NULL; return std; }

25 Freeing students After we’re done, we need to free the memory we’ve allocated One implementation is as we saw in class void free_list(Student *head) { Student *to_free = head; while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

26 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

27 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

28 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

29 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

30 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

31 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

32 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

33 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

34 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

35 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

36 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

37 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

38 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

39 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

40 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

41 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

42 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

43 Freeing students NULL headto_free while (to_free != NULL) { head = head->next; free(to_free); to_free = head; }

44 Exercise Use Student_Package2.c and implement find_student, which receives a list and an ID number and returns a pointer to a student whose ID matches or NULL if no such student is found. Student *find_student(Student *head, char id[]); Hint: Use strcmp(s1, s2) which compares s1 and s2 and returns 0 if they are equal

45 Solution /* find a student whose id matches the given id number */ Student *find_student(Student *head, char id[]) { Student *to_search = head; /* Start from head of list */ while (to_search != NULL) /* go over all the list */ { if (strcmp(to_search->ID, id) == 0) /* same id */ return to_search; to_search = to_search->next; } /* If we're here, we didn't find */ return NULL; }


Download ppt "Exercise 11 Dynamic allocation, structures, linked lists."

Similar presentations


Ads by Google