Download presentation
Presentation is loading. Please wait.
1
Dynamically Allocated Arrays May 2, 2011
2
Quiz 5 Today
3
Intro to Pointers A pointer is a variable that holds an address Declaration uses * int* p; int i; & is “Address of” operator. Gets the address of a variable. p = &i;
4
Intro to Pointers * is used to dereference a pointer: *p = 15; Above is that what p points to is assigned the value, 15. pointers.cpp
5
Arrays Are Pointers In a program, an array, a, and a pointer, p, are the same kind of pointer. int* p; //p is an int pointer int a[10]; They both point at an int.
6
Arrays Are Pointers p can get the address that a is pointing at. p = a; It is illegal to change a. a = p; Once p is assigned the value of a it can be used like an array variable. arrayPtr.cpp
7
Dynamically Allocated Arrays Sometimes the amount of memory needed by an array can vary greatly. e.g. Number of campers in Ponderosa park in January vs. August. To save memory, use dynamic array.
8
Dynamically Allocated Arrays Declare using a pointer Can return to memory Can vary size //allocate array with 20 ints int *pt = new int[20];
9
Initialize Array double *buff = new double[10]; for (int i=0; i<10; i++) { *buff = 100.0; buff++; }
10
Initialize Array Alternative double *buff = new double[10]; for (int i=0; i<10; i++) { buff[i] = 100.0; }
11
Release memory delete []pt; delete []buff; If an array is no longer needed this can free up memory for other programs.
12
NULL Can assign a pointer to a NULL value, which is pointing to nothing.
13
Memory Leak void myfunction( ){ int *pt; pt = new int[100];. //no delete } //in main: while(cond.) myfunction();
14
Destructors Return data memory When object goes out of scope. Look at messageDest.cpp
15
Copying Objects with Dynamic Arrays Assignment Operator copies objects message2 = message; Copies a pointer, not the array Example in message.cpp Messy error.
16
Copying Objects with Dynamic Arrays Deep Copying Create a new array and copy contents to the array messageFixed.cpp copyFrom function fixes
17
Overload == To make sure no problems happen, overload == Do deep copy when an assignment is done.
18
Copy Constructor Copying of objects occur: Passing a copy of an argument using pass-by- value. Returning an object from a function: return msg1; By default these are shallow copying. Better to provide a copy constructor that does a deep copy. messageCopyConstr.cpp
19
Copy Constructor Odd things can happen without copy constructor. If two objects point to same array, something done to one object effects the other. Like the problem with message
20
Next Time Review For Final Info is on website. Topics don't include linux, vim nor hardware.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.