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

Info icon This 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 */
Image of page 1

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

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

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern