lecture24-mar24

lecture24-mar24 - Announcements Lecture 24 Fridays lecture...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Announcements Lecture 24 • Friday’s lecture cancelled – recitations held • Exam 2 – April 5 th • Assignment 5 – Designs due Friday in recitation – Q&A • Topics for today Finish dynamic storage allocation Pointers - advanced uses Linked lists – another way to represent a list Function pointers The malloc Function malloc() is a storage allocation function. When called, it allocates a block of size bytes on the heap and returns a “generic” pointer to it: void *malloc (size_t size); • For example int *p; p = malloc(sizeof(int)); /* means allocate memory for an int now – on the heap */ p This is on the heap, but where is p? Dynamically Allocated Arrays An array can be dynamically allocated using calloc ( ) – calloc is similar to malloc, but allocates space for an array with num elements, each of which is size bytes long: void *calloc(size_t num, size_t size); The block of memory allocated by calloc is initially cleared – i.e., set to all 0 bits Example: int *a; /* a is the array name */ int num, i; printf ("Enter the number of array elements: "); scanf ("%d", &num); a = calloc(num, sizeof(int)); printf("Enter the individual array elements: "); for (i = 0; i < num; i++) { scanf("%d", &a[i]); } The free Function • When a block of memory obtained by calling malloc or calloc is no longer referenced by a pointer, it is said to be garbage. int *p, *q; p = malloc(sizeof(int)); q = malloc(sizeof(int)); p = q; /* the old block that p pointed to is now garbage */ • Garbage should be avoided; “recycle” memory instead. • When a block of memory is no longer needed, it can
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 08/30/2010 for the course EE 312 taught by Professor Shafer during the Spring '08 term at University of Texas.

Page1 / 2

lecture24-mar24 - Announcements Lecture 24 Fridays lecture...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online