HampK Chapter 14 Instructor Gokcen Cilingir Cpt S 121 July 26 2011 Washington State University Dynamic Data Structures 1 Structures that expand and contract as a program executes ID: 537663
Download Presentation The PPT/PDF document "Dynamic Data Structures" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Dynamic Data StructuresH&K Chapter 14
Instructor – Gokcen CilingirCpt S 121 (July 26, 2011)Washington State UniversitySlide2
Dynamic Data Structures (1)Structures that expand and contract as a program executesUsing dynamic data structures, you can allocate memory as needed (no need to constraint the maximum size of an array at compile time)Dynamic memory allocation allows us to dynamically allocate an array at run time.
Image source: http://www.sparknotes.com/cs/pointers/whyusepointers/section3.rhtmlSlide3
Dynamic Data Structures (2)When allocating memory dynamically, a program can use the space to store any of the simple and structured data types (i.e. structs,
ints, doubles, etc.)We can combine separately allocated structured blocks (called nodes) to form composite structures that expand and contract while the program executes. 5
2
7
head
A
node
containing a data field
and a pointer to the next nodeSlide4
C. Hundhausen, A. O’Fallon4A pointer variable contains the address of another cell containing a data value
Note that a pointer is “useless” unless we make sure that it points somewhere:int num = 3, int *nump = #The direct value of num is 3, while the direct value of nump is the address (1000) of the memory cell which holds the 3
Pointer Review I
3
nump
num
2000
1000Slide5
C. Hundhausen, A. O’Fallon5Pointer Review II
Reference Explanation Valuenum Direct value of num
3
nump
Direct value of
nump
1000
*
nump
Indirect value of
nump
3
&
nump
Address of nump 2000
3
nump
num
2000
1000Slide6
6Pointers as Function Parameters
Recall that we define an output parameter to a function by passing the address (&) of the variable to the functionThe output parameter is defined as a pointer in the formal parameter listSlide7
7Pointers Representing Arrays and Strings
Consider these variable declarations:double gradeList[20];char name[40];When we want to pass either of these arrays to functions, we use the array name with no subscript average (
gradeList
);
reverse (name);
C interprets the array name as the
address of the initial array
element, so a whole array is always passed to a function as a pointer!
Therefore, if we were passing an array to a function, the corresponding formal parameter might be declared in two ways. So, all of the following prototypes are valid for the above functions:
double average (double list[]);
double average (double *list);
void reverse (char name[]);
void reverse (char *name);
array declarations
pass an array to a function
arrays as formal parametersSlide8
8Pointers to StructuresRecall that when we have a pointer to a structure, we can use the indirect component selection operator
-> to access components within the structuretypedef struct{ double grade; int age;} Student;
int
main (void)
{
Student p1, *
struct_ptr
;
p1.grade = 95;
p1.age = 20;
struct_ptr
= &p1;
struct_ptr
->x; // Access grade field in Student
.
. .
}Slide9
C. Hundhausen, A. O’Fallon9malloc function (1)
Dynamic memory allocation can be performed with the help of the function malloc() found in <stdlib.h>malloc() has the following prototype: void *malloc (size_t size);
The argument to
malloc
is a number indicating the amount of memory space needed to be allocated
We can apply the
sizeof
operator to a data type to determine the number (the number represents the number of bytes needed)Slide10
C. Hundhausen, A. O’Fallon10malloc function (2)
The statement:malloc (sizeof (int)) allocates exactly enough space to hold one integerA call to malloc returns a pointer to the block of memory allocated (if no memory can be allocated, NULL is returned)
The return type is
void *
which is generic, thus we need to assign the pointer to a specific type by explicitly typecasting:
int
*
nump
= (
int
*)
malloc
(sizeof (
int));char *chp
= (char *) malloc (sizeof
(char));Slide11
C. Hundhausen, A. O’Fallon, G. Cilingir11
malloc function (3)The area in which the dynamic memory is allocated is called the heapThe stack is the area that stores function data when functions are enteredRemember that the memory allocated for a given function's data (on the stack) goes away when the function is exitedFunction data area
Heap
nump
chpSlide12
C. Hundhausen, A. O’Fallon12Accessing a Component of a Dynamically Allocated Structure
Accessing a component of a dynamically allocated structure is done in the same way as accessing a component of a statically allocated structure:Student *struct_ptr = (Student *) malloc (sizeof (Student));struct_ptr
-
>
grade
is equivalent to
(*
struct_ptr
).gradeSlide13
C. Hundhausen, A. O’Fallon13Dynamic Array Allocation with calloc
calloc() may be used to allocate contiguous blocks of memory for array elementsThe function is also found in <stdlib.h>The function prototype for calloc() is as follows: void *calloc (size_t nitems
,
size_t
size);
The two arguments to
calloc()
are the number of array elements needed and the size of one element, respectively.Slide14
C. Hundhausen, A. O’Fallon14calloc
As with malloc, calloc also returns a void * to the beginning of the allocated blocks of memoryThus, we can allocate 10 blocks of contiguous memory as follows:Student *struct_ptr = (Student *) calloc (10, sizeof (Student));
Note the above statement is similar to
Student array[10
];
except that it is allocated dynamically, instead of staticallySlide15
C. Hundhausen, A. O’Fallon15Applying Array Notation to Pointers
If we executed the calloc statement on the previous slide, we could then use array notation to access each element in the block of dynamically allocated memory:struct_ptr[0] would access the first element in the array and struct_ptr[9] would access the last element in the arraySlide16
C. Hundhausen, A. O’Fallon16Freeing Allocated Memory
We need to be able to give up memory after we are done using itWe can use the function free() to return the allocated memory to the heapFor example:free (struct_ptr);returns the dynamically-allocated memory blockpointed to by struct_ptrMemory leaks occur if we do not free memory before the local variable that accesses the allocated memory goes out of scopeMemory leaks are a common source of run-time program bugs; they can also slow down a program's executionSlide17
17ReferencesJ.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (6th Ed.), Addison-Wesley, 2010P.J. Deitel & H.M. Deitel,
C How to Program (5th Ed.), Pearson Education , Inc., 2007.