Quiz 4 Pointers and Dynamically Allocated Memory - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

Quiz 4 Pointers and Dynamically Allocated Memory

Description:

Some flexibility, but not enough. Has to prepare for the worst. Waste of ... relations between arrays and pointers in C, make it almost as easy to operate as ... – PowerPoint PPT presentation

Number of Views:59
Avg rating:3.0/5.0
Slides: 10
Provided by: hiy
Category:

less

Transcript and Presenter's Notes

Title: Quiz 4 Pointers and Dynamically Allocated Memory


1
Quiz 4Pointers and Dynamically Allocated Memory
  • CGS 3460, Lecture 32
  • Mar 31, 2006
  • Hen-I Yang

2
Previously
  • Arrays and Pointers

3
Agenda
  • Dynamic Memory Allocation
  • Dynamic Allocated Arrays

4
Why dynamically allocate memory?
  • Use of lots of variables
  • Use of arrays
  • Some flexibility, but not enough
  • Has to prepare for the worst
  • Waste of memory space not used
  • Use of dynamically allocated memory
  • Most frequently associated with array, string and
    struct

5
How to dynamically allocate memory?
  • ltstdlib.hgt
  • malloc(size_t size)
  • There are other functions, but malloc is by far
    most frequently used
  • It allocates, but not clears
  • If no memory of the size available, will return
    null
  • It is programmers responsibility to check for
    null

6
Dynamically allocated array
  • Difficulty in estimating the proper size of array
    ahead of time.
  • Dynamically means you can decide the size
    during the execution time, not compilation time
  • Close relations between arrays and pointers in C,
    make it almost as easy to operate as the original
    array

7
Malloc an Array
  • int a
  • a malloc(n sizeof(int))
  • Can we just say a malloc(n 4)?
  • Not a good idea
  • After malloc, you have all the space needed for
    the array allocated
  • After that, you can use ai or (ai) to access
    the elements

8
Summary
  • Dynamic Memory Allocation
  • Dynamic Allocated Arrays

9
Before you go
  • Read Chapter 17
  • Exercise Have a look at 17.12
Write a Comment
User Comments (0)
About PowerShow.com