1 / 18

DYNAMICALLY ALLOCATED ARRAYS

DYNAMICALLY ALLOCATED ARRAYS. Chapter 2. DYNAMIC MEMORY ALLOCATION. Most often we face situations in programming where the data is dynamic in nature. That is ,the no of data items keep changing during the execution of the program.

howell
Download Presentation

DYNAMICALLY ALLOCATED ARRAYS

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. DYNAMICALLY ALLOCATED ARRAYS Chapter 2

  2. DYNAMIC MEMORY ALLOCATION • Most often we face situations in programming where the data is dynamic in nature. • That is ,the no of data items keep changing during the execution of the program. • Eg: consider a program for processing a list of customers of a corporation. The list grows when names are added and shrinks when names are deleted. • When list grows we need to allocate more memory space to the list to accomadate additional data items. • Such situations handled using dynamic data structures, in conjunction with dynamic memory management.

  3. Con.. • Dynamic data structures provide flexibility in adding ,deleting or rearranging data items at runtime. • Dynamic memory management techniques permit us to allocate additional memory space or to release unwanted space at runtime ,thus, optimizing the use of storage space. • C language requires the no of elements in an array to be specified at compile time. But we may not be able to do so always. • Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space.

  4. Con.. • Many languages permit a programmer to specify an array’s size at runtime. • Such languages have the ability to calculate and assign, during execution ,the memory space required by the variables in a program. • The process of allocating memory at runtime is known as dynamic memory allocation. • Although C does not inherently have this facility, there are 4 library routines known as "memory management functions". That can be used for allocating and freeing memory during program execution.

  5. Memory allocation functions • Malloc:Allocates requested size of bytes and returns a pointer to the first byte of the allocated space. • Calloc: Allocates space for an array of elements ,initializes them to zero and returns a pointer to the memory. • Free: frees previously allocated space. • Realloc:modifies the space of previously allocated space

  6. One dimensional arrays • #define MAX_SIZE 100 • float sum(float [],int); • float input [max_size],answer; • Void main(void) • { • int i; • for(i= 0;i<max_size ; i++) • input[i] = i ; • Answer=sum(input , max_size) • Printf(“the sum is :%f \n”, answer); • }

  7. Con.. • float sum(float list [],int n) • { • int i; • float tempsum = 0; • for( i= 0;i<n ;i ++) • Tempsum+=list[i]; • return tempsum; • }

  8. Con.. • In the previous program we defined the constant MAX_SIZE to have the value 101. • As a result the program, the program can be used to sort a collection of up to 101 no. • If the user wishes more than 101 no ,we have to change the definition of MAX_SIZE using some larger value and recompile the program. • how large should this value be ? If we set this MAX_SIZE to a very larger no (say several million ) • We reduce the likelihood the program will fail at runtime because the input value of n is less likely to exceed this large value of MAX_SIZE

  9. Con.. • When writing computer programs ,we often find ourselves in a situation were we cannot reliably determine how large an array to use • A good solution to this is to defer this decision to runtime and allocate the array when we have a good estimate of the required array size. • So for eg we could change the first few lines of the main program to:

  10. Con.. • int i, n *list; • Printf(“enter size for generation”); • Scanf(“%d”,& n); • If (n < 1) • { • fprintf(stderr,”improper value of n \n”); • Exit(exit_failure); • } • Malloc(list,n*sizeof(int)); • Now ,the program fails only when n<1or we donot have sufficient memory to hold the list of nos that are to be stored

  11. 2-dimensional arrays • In this representation ,a two dimensional array is represented as a one dimensional array in which each element is itself ,a one-dimensional array . • int x [3] [5] ; • We actually create a one –dimensional array x whose length is 3;each element of x is a one dimensional array whose length is 5. • C finds the element x[i] [j] by first accessing the pointer in x[i]. • This pointer gives us the address ,in memory of the zeroth element of the row i of the array .

  12. Con.. • Then by adding j*sizeof(int) to this pointor, the address of the [j] th element of row i. • i.e element x[i] [j] is determined. • The following program gives a function that creates a two dimensional array at runtime. • int **myarray; • Myarray=make2darray(5,10); • Myarray[2] [4]=6; • The second line allocates memory for a 5 by 10 two-dimensional array of integers and the third line assigns the value 6 to the [2][4] element of this array.

  13. Dynamically create a 2-d array • int ** make2darray(int rows, int cols) • {/*create a two dimensional rows x cols array */ • Int **x, i; • /*get memory for row pointors */ • Malloc(x, rows*sizeof(*x));; • /*get memory for each row */ • for(i=0;i< rows; i++) • Malloc(x[i],cols*sizeof(**x)); • return x; • }

  14. calloc • The function calloc allocates a user-specfied amount of memory and initializes the allocated memory to 0. • (i.e all allocated bits are set to 0) a pointor to the start of the allocated memory is returned. • In case there is insufficient memory to make the allocation ,the returned value is null.so,for eg • Int *x; • X= calloc(n,sizeof(int)); • Could be used to declare 1D array of integers.

  15. calloc • The function calloc allocates a user-specfied amount of memory and initializes the allocated memory to 0. • (i.e all allocated bits are set to 0) a pointor to the start of the allocated memory is returned. • In case there is insufficient memory to make the allocation ,the returned value is null.so,for eg • Int *x; • X= calloc(n,sizeof(int)); • Could be used to declare 1D array of integers.

  16. calloc • The capacity of this array is n and x[0:n-1] are initially 0. • As was the case with malloc ,it is useful to define the macro calloc as below and use this to write a programs. • #define calloc(p,n,s) \ • If( !((p) =calloc(n,s))) { \ • Fprintf(stderr,”insufficient memory”); • Exit(exit_failure); \ • }

  17. realloc • The function realloc resizes memory previously allocated by either malloc or calloc. • realloc(p, s) • Changes the size of the memory block pointed at by p to s. • The contents of the first min { s,oldsize} bytes of the block are unchanged as a result of this resizing. • when realloc is able to do the resizing,it returns a pointor to the start of the new block. • And when it is unable to do the resizing, the old block is unchanged and the function returns a null value.

  18. Con.. • As with malloc and calloc,it is useful to define a macro REALLOC as below. • #define RELLOC(P,S) \ • If(!((p) =realloc(p,s))) { \ • fprintf(stderr,”insufficient memory”); \ • exit(exit_failure);\ • }

More Related