Chapter 14 Dynamic Data Structures Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-1
Dynamic Data Structure Usually, so far, the arrays and strings we re using have fixed length (i.e., length is known at compile time) E.g. char mystr[11]; // allocates memory for 11 chars printf( Enter a string: ); fgets(mystr, 11, stdin);//includes null character What if the user wants to enter a string more than 10 chars long or if the length is known only at run time? 2
Dynamic Data Structure Memory allocation in C: malloc() calloc() realloc() Deallocates using the free()function. 3
Dynamic Data Structure Dynamic data structure is a structure that can expand and contract as a program executes. The creation and manipulation of dynamic data structures requires use of pointers. A pointer is a variable which stores the memory address of a data value. 4
Comparison of pointer and Nonpointer Variables The actual data value of a pointer variable is accessed indirectly. The actual data value of a non-pointer variable can be accessed directly. Pointer variable Nonpointer variable Reference Explanation Value num A simple variable 3 nump pointer holding a memory address Addr. of the location pointed to *nump Indirect value of nump 3 Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5
Pointer Review A call to a function with pointer parameters may need to use the & operator. e.g., if we have an int variable value1 and f1(int *value), f1(&value1) is a legal call. A pointer can be used to represent an array. e.g., char n[] is equal to char *n. A pointer can also represent a structure. e.g., File * is a pointer to a File structure. 6
Memory Allocation C provides a memory allocation function called malloc, which resides in the stdlib library. This function requires an argument which indicates the amount of memory space needed. The returned data type is (void *) and should be always cast to the specific type. It doesn t clear the memory. 7
Memory Allocation - malloc function Description The C library function allocates the requested memory and returns a pointer to it. Declaration void *malloc(size_t size) Parameters size -- This is the size of the memory block, in bytes. Return Value This function returns a pointer to the allocated memory, or NULL if the request fails. 8
Memory Allocation E.g. //Variable declarations #define STRSIZ 10 typedef struct { } planet_t; #include <stdio.h> #include <stdlib.h> int main() char name[strsiz]; double diameter; /* equatorial diameter in km */ int moons; /* number of moons */ double orbit_time, /* years to orbit sun once */ double rotation_time; /* hours to complete one revolution on axis */ { int *nump; char *letp; planet_t *planetp; planet_t blank_planet = {"", 0, 0, 0, 0}; 9
Memory Allocation //Allocation: nump = (int *) malloc (sizeof (int)); letp = (char *) malloc (sizeof (char)); planetp = (planet_t *) malloc (sizeof (planet_t)); //Assignment: *nump = 307; *letp = Q ; *planetp = blank_planet; 10
Memory Allocation Memory space after allocation Memory space after assignment Pointers Pointers 11
Heap and Stack Heap is the region of memory where function malloc dynamically allocates space for variables. Stack is the region of memory where function data areas are allocated and reclaimed. 12
Memory Allocation - calloc function Description This function allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero. Declaration void *calloc(size_t nitems, size_t size) Parameters nitems -- This is the number of elements to be allocated. size -- This is the size of elements. Return Value This function returns a pointer to the allocated memory, or NULL if the request fails. This function is used to declare dynamic arrays. 13
Free Memory Description The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc. Declaration void free(void *ptr) Parameters ptr -- This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs. Return Value This function does not return any value. Once the memory space is released, we can not access the space again. Otherwise, it is considered as an illegal memory access. 14
//Allocating space for a simple integer variable #include <stdio.h> #include <stdlib.h> int main () { int * p; p = (int *) malloc (sizeof (int)); // partitioning of type int if (p == NULL) // failed to reserve area { printf ("Failed to allocate space for %d bytes", sizeof (int)); return 1; } *p = 150; printf ("%d \n", *p); free (p); // free allocated memory space return 0; } 15
Memory Allocation - realloc function Description The C library function attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc. Declaration void *realloc(void *ptr, size_t size) Parameters ptr -- This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function. size -- This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned. Return Value This function returns a pointer to the newly allocated memory, or NULL if the request fails. 16
//Practicing reallocate function #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; /* Initial memory allocation for 15 characters*/ str = (char *) malloc(15); //For simplicity, we skipped error checking strcpy(str, "tutorialspoint"); printf("string = %s, Address = %p\n", str, str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("string = %s, Address = %p\n", str, str); free(str); return(0); } 17
Practicing Dynamic Array Allocation C provides a function calloc which creates an array of elements of any type and initializes the array elements to zero. Function calloc takes two arguments: the number of array elements and the size of one element. E.g., int *array_of_nums; array_of_nums = (int *) calloc(10, sizeof(int)); 18
//Let s create an array in a size according to the user request #include <stdio.h> #include <stdlib.h> int main() { int i, n; int *a; printf("number of elements to be entered:"); scanf("%d",&n); a = (int*)calloc(n, sizeof(int));//allocate required memory and initialize it if (a!=null) { printf("enter %d numbers:\n",n); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("the numbers entered are: "); for(i=0;i<n;i++) printf("%d ",a[i]); } else printf("memory allocation cannot be done."); printf("\n"); return(0); } 19
// realloc example: add an integer array element one by one #include <stdio.h> /* printf, scanf, puts */ #include <stdlib.h> /* realloc, free, exit, NULL */ int main () { int input,n,count = 0; int* numbers = NULL,* more_numbers = NULL; do { printf ("Enter an integer value (0 to end): "); scanf ("%d", &input); count++; more_numbers = (int*) realloc (numbers, count * sizeof(int)); if (more_numbers!=null) { numbers=more_numbers; numbers[count-1]=input; } else { free (numbers); puts ("Error (re)allocating memory"); exit (1); } } while (input!=0); printf ("Numbers entered: "); for (n=0;n<count;n++) printf ("%d ",numbers[n]); free (numbers); free(more_numbers); printf("\n"); return 0; } 20
//This program takes input and outputs everything backwards. //http://forum.codecall.net/topic/51010-dynamic-arrays-using-malloc-and-realloc/ #include <stdio.h> #include <stdlib.h> int main() { char *data,*temp,c; int i; for (i=i-1;i>=0;i--)//in previous loop i s value //was out of array bound putchar(data[i]); // Output data backwards // one character at a time free(data); // Free the pointer return 0; } data=(char *) malloc(sizeof(char)); if (data==null) printf("error allocating memory!\n"); else { printf("enter a sentence:\n"); for (i=0; ;i++) {//infinite loop c=getchar(); if (c=='\n') break; //Program stops reading when user hits return key data[i]=c; // put the character into the data array temp=(char *) realloc(data,(i+2)*sizeof(char)); //Reallocate memory,+2 bec.: 1 for arr. index starts from 0,1 to add arr. elem. if (temp!= NULL ) data=temp; else { free(data); printf("error allocating memory!\n"); return 1; }//else }//for 21
Multiple Pointers to a Cell double *xp, xcopyp; xp=(double *)malloc(sizeof(double)); *xp=49.5; free(xp); xcopyp=*xp; Be careful when releasing memory since the other pointer may still access the memory space. Copyright 2004 Pearson Addison-Wesley. All rights reserved. 22