06_memory - CSCI-1200 Data Structures - Fall 2010 Lecture 6...

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

View Full Document Right Arrow Icon
Review from Lecture 5 Pointer variables, arrays, pointer arithmetic and dereferencing, character arrays, and calling conventions. Today’s Lecture — Pointers and Dynamic Memory Arrays and pointers, different types of memory, dynamic allocation of arrays, and examples. 6.1 Three Types of Memory Automatic memory: memory allocation inside a function when you create a variable. This allocates space for local variables in functions (on the stack ) and deallocates it when variables go out of scope. For example: int x; double y; Static memory: variables allocated statically (with the keyword static ). They are are not eliminated when they go out of scope. They retain their values, but are only accessible within the scope where they are defined. static int counter; Dynamic memory: explicitly allocated (on the heap ) as needed. This is our focus for today. 6.2 Dynamic Memory Dynamic memory is: created using the new operator, accessed through pointers, and removed through the delete operator. Here’s a simple example involving dynamic allocation of integers: int * p = new int; *p = 17; cout << *p << endl; int * q; q = new int; *q = *p; *p = 27; cout << *p << " " << *q << endl; int * temp = q; q = p; p = temp; cout << *p << " " << *q << endl; delete p; delete q; heap stack p q temp 17 The expression new int asks the system for a new chunk of memory that is large enough to hold an integer and returns the address of that memory. Therefore, the statement int * p = new int; allocates memory from the heap and stores its address in the pointer variable p . The statement
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.

Page1 / 4

06_memory - CSCI-1200 Data Structures - Fall 2010 Lecture 6...

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