dynamic memory allocation, structure pointers

23
20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur 1 Dynamic Memory Allocation, Structure pointers Lecture 17b 20.3.2001.

Upload: lucrece-amadeus

Post on 03-Jan-2016

52 views

Category:

Documents


3 download

DESCRIPTION

Dynamic Memory Allocation, Structure pointers. Lecture 17b 20.3.2001. Basic Idea. Many a time we face situations where data is dynamic in nature. Amount of data cannot be predicted beforehand. Number of data item keeps changing during program execution. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

1

Dynamic Memory Allocation,Structure pointers

Lecture 17b20.3.2001.

Page 2: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

2

Basic Idea Many a time we face situations where

data is dynamic in nature. Amount of data cannot be predicted

beforehand. Number of data item keeps changing

during program execution. Such situations can be handled more

easily and effectively using dynamic memory management techniques.

Page 3: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

3

C language requires the number of elements in an array to be specified at compile time. Often leads to wastage or memory

space or program failure. Dynamic Memory Allocation

Memory space required can be specified at the time of execution.

C supports allocating and freeing memory dynamically using library routines.

Page 4: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

4

Memory Allocation Process in C

Local variables

Free memory

Global variables

InstructionsPermanent storage area

Stack

Heap

Page 5: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

5

The program instructions and the global variables are stored in a region known as permanent storage area.

The local variables are stored in another area called stack.

The memory space between these two areas is available for dynamic allocation during execution of the program. This free region is called the heap. The size of the heap keeps changing

Page 6: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

6

Memory Allocation Functions

malloc: Allocates requested number 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 then returns a pointer to the memory.

free : Frees previously allocated space. realloc: Modifies the size of previously

allocated space.

Page 7: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

7

Dynamic Memory Allocation used to dynamically create

space for arrays, structures, etc.

int main () { int *a ; int n; .... a = (int *) calloc (n, sizeof(int)); ....}

a = malloc (n*sizeof(int));

Page 8: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

8

Space that has been dynamically allocated with either calloc() or malloc() does not get returned to the function upon function exit.

The programmer must use free() explicitly to return the space. ptr = malloc (...) ; free (ptr) ;

Page 9: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

9

void read_array (int *a, int n) ;int sum_array (int *a, int n) ;void wrt_array (int *a, int n) ;

int main () { int *a, n; printf (“Input n: “) ; scanf (“%d”, &n) ; a = calloc (n, sizeof (int)) ; read_array (a, n) ; wrt_array (a, n) ; printf (“Sum = %d\n”, sum_array(a, n);}

Page 10: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

10

void read_array (int *a, int n) { int i; for (i=0; i<n; i++)

scanf (“%d”, &a[i]) ;}void sum_array (int *a, int n) { int i, sum=0; for (i=0; i<n; i++) sum += a[i] ; return sum;}void wrt_array (int *a, int n) { int i; ........}

Page 11: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

11

Arrays of Pointers Array elements can be of any type

array of structures array of pointers

Page 12: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

12

int main (void) {char word[MAXWORD];char * w[N]; /* an array of pointers */int i, n; /* n: no of words to sort */

for (i=0; scanf(“%s”, word) == 1); ++i) { w[i] = calloc (strlen(word)+1, sizeof(char)); if (w[i] == NULL) exit(0);

strcpy (w[i], word) ;}

n = i;sortwords (w, n) ;wrt_words (w, n);return 0;

}

Page 13: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

13

w

0

1

2

3

17

Input : A is for apple or alphabet pie which all get a slice of come taste it and try

A \0

i s \0

f o r \0

a p p l e \0

t r y \0

Page 14: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

14

void sort_words (char *w[], int n) { int i, j; for (i=0; i<n; ++i)

for (j=i+1; j<n; ++j)if (strcmp(w[i], w[j]) > 0) swap (&w[i], &w[j]) ;

}void swap (char **p, char **q) { char *tmp ; tmp = *p; *p = *q; *q = tmp;}

Page 15: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

15

w

w[i]

f o r \0

a p p l e \0

Before swapping

w[j]

Page 16: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

16

w

w[i]

f o r \0

a p p l e \0

After swapping

w[j]

Page 17: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

17

Pointers to Structure

Page 18: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

18

Pointers and Structures You may recall that the name of an array

stands for the address of its zero-th element. Also true for the names of arrays of structure

variables. Consider the declaration:

struct stud { int roll; char dept_code[25]; float cgpa; } class[100], *ptr ;

Page 19: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

19

The name class represents the address of the zero-th element of the structure array.

ptr is a pointer to data objects of the type struct stud.

The assignmentptr = class ;

will assign the address of class[0] to ptr. When the pointer ptr is incremented by

one (ptr++) : The value of ptr is actually increased

by sizeof(stud). It is made to point to the next record.

Page 20: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

20

Once ptr points to a structure variable, the members can be accessed as: ptr –> roll ; ptr –> dept_code ; ptr –> cgpa ;

The symbol “–>” is called the arrow operator.

Page 21: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

21

Warning When using structure pointers, we should take

care of operator precedence. Member operator “.” has higher precedence than “*”.

ptr –> roll and (*ptr).roll mean the same thing. *ptr.roll will lead to error.

The operator “–>” enjoys the highest priority among operators.

++ptr –> roll will increment roll, not ptr. (++ptr) –> roll will do the intended thing.

Page 22: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

22

Program to add two complex numbers using pointers

typedef struct { float re; float im;} complex;main() { complex a, b, c; scanf (“%f %f”, &a.re, &a.im); scanf (“%f %f”, &b.re, &b.im); add (&a, &b, &c) ; printf (“\n %f %f”, c,re, c.im);}

Page 23: Dynamic Memory Allocation, Structure pointers

20.3.2001. Sudeshna Sarkar, CSE, IIT Kharagpur

23

void add (complex * x, complex * y, complex * t) {

t->re = x->re + y->re ;

t->im = x->im + y->im ;

}