Download presentation
Presentation is loading. Please wait.
1
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Memory Allocation Ming Li Department of Computer Science California State University, Fresno Fall 2006
2
Introduction to Data Structure, Spring 2007 Slide- 2 California State University, Fresno Vertical and Horizontal View of Memory Address 0 Addressn Address 2 Address 1 Addr 0 1 2 n Vertical View of Memory Horizontal View of Memory...
3
Introduction to Data Structure, Spring 2007 Slide- 3 California State University, Fresno Data Addresses in Memory
4
Introduction to Data Structure, Spring 2007 Slide- 4 California State University, Fresno Declare a pointer by stating the type followed by the variable name, but with a "*" added immediately before the name. The pointer ptr is a variable whose value is the address of a data item of the designated type. Declaring Pointer Variables int *intPtr; char *charPtr; type *ptr;
5
Introduction to Data Structure, Spring 2007 Slide- 5 California State University, Fresno Assigning Values to Pointers &m is the address of the integer in memory. The assignment statement Sets intPtr to point at an actual data item. intPtr = &m; int m = 50, *intPtr;
6
Introduction to Data Structure, Spring 2007 Slide- 6 California State University, Fresno Accessing Data with Pointers int x = 50, y = 100, *px = &x, *py = &y;
7
Introduction to Data Structure, Spring 2007 Slide- 7 California State University, Fresno Operator ‘new’ p = new time24; // *p is 00:00 (midnight) q = new time24(8, 15); // *q is 8:15 AM Question: Difference between “Heap” and “Stack”?
8
Introduction to Data Structure, Spring 2007 Slide- 8 California State University, Fresno Operator ‘delete’ Deallocating a dynamic array, use a slightly different form of delete. Place square brackets [] between delete and the pointer variable name. The system deallocates all of the memory originally assigned to the dynamic array. arr = new T[ARRSIZE]; // allocated space for ARRSIZE objects delete [] arr; // deallocate dynamic array storage
9
Introduction to Data Structure, Spring 2007 Slide- 9 California State University, Fresno Illustrating the Destructor
10
Introduction to Data Structure, Spring 2007 Slide- 10 California State University, Fresno Difference between C and C++ In C: Use malloc or calloc to allocate memory char *cp = malloc (100); int *cp = calloc (100, sizeof(int)); Use free to release memory free(cp); malloc and free should be used together In C++ new and delete should be used together Mixing new with free or malloc/calloc with delete will crash the memory!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.