Dynamic Allocation and Linked Lists - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

Dynamic Allocation and Linked Lists

Description:

C uses the functions malloc() and free() to implement dynamic allocation. ... Memory allocated with malloc must be released after you are done with them. ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 15
Provided by: mikeh45
Learn more at: http://www.cs.gsu.edu
Category:

less

Transcript and Presenter's Notes

Title: Dynamic Allocation and Linked Lists


1
Dynamic Allocation and Linked Lists
2
Dynamic memory allocation in C
  • C uses the functions malloc() and free() to
    implement dynamic allocation.
  • malloc is defined in stdlib.h and malloc.h header
    files.
  • malloc returns a void pointer.
  • the pointer returned from malloc requires a type
    cast to make it usable.

3
Type Casting
  • To make one data type appear like another you can
    use a type cast.
  • int I
  • int a (int)sqrt((float) I )
  • To make the void pointer returned by malloc look
    like your struct you must typecast it to a
    pointer to a struct.

4
Example
  • struct rec
  • char LastName41
  • char FirstName41
  • struct rec r
  • r (struct rec) malloc( sizeof(struct rec))

5
Freeing Memory
  • Memory allocated with malloc must be released
    after you are done with them.
  • this memory is released by calling the function
    free().
  • Since free expects as an argument the pointer
    returned by malloc it expects a void pointer.
  • free( r )

6
Linked List
  • A linked list is a basic data structure.
  • For easier understanding divide the linked list
    into two parts.
  • Nodes make up linked lists.
  • Nodes are structures made up of data and a
    pointer to another node.
  • Usually the pointer is called next.

7
Nodes
  • struct node
  • struct rec r
  • struct node next

8
LIST
  • The list will contain a pointer to the start of
    the list.
  • For our purposes all data will be added to the
    start of the list.
  • Initialize the start pointer to NULL.

9
Creating a New Node
  • Allocate space for a new node.
  • Set the next pointer to the value of NULL
  • Set the data value for the node.

10
Adding Nodes to the List
  • If the start node is null then the start node
    becomes the new node.
  • If start is not null then start becomes the new
    nodes next and the start becomes the new node.

11
(No Transcript)
12
(No Transcript)
13
(No Transcript)
14
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com