Download presentation
Presentation is loading. Please wait.
Published byVirgil Banks Modified over 9 years ago
1
Dynamically Allocated Arrays December 4, 2013
2
Skip the Rest of this PowerPoint
3
Next Time Read Chapter 8,pp. 351-357
4
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;
5
Intro to Pointers * is used to dereference a pointer: *p = 15; Above: what p points to is assigned the value, 15. pointers.cpp
6
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.
7
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
8
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.
9
Dynamically Allocated Arrays Declare using a pointer Can return to memory Can vary size //allocate array with 20 ints int *pt = new int[20];
10
Initialize Array double *buff = new double[10]; for (int i=0; i<10; i++) { *buff = 100.0; buff++; }
11
Initialize Array Alternative double *buff = new double[10]; for (int i=0; i<10; i++) { buff[i] = 100.0; }
12
Release memory delete []pt; delete []buff; If an array is no longer needed this can free up memory for other programs.
13
Another Example int* p = new int[10]; for (int i = 0; i< 10; i++) { p[i] = i * i; } cout << *p << " " << *(p+1) << " " << p[2] << endl;
14
NULL Can assign a pointer to a NULL value, which is pointing to nothing.
15
Memory Leak void myfunction( ){ int *pt; pt = new int[100];. //no delete } //in main: while(cond.) myfunction();
16
Destructors Return data memory When object goes out of scope. Look at messageDest.cpp
17
Copying Objects with Dynamic Arrays(Skip) Assignment Operator copies objects message2 = message; Copies a pointer, not the array Example in message.cpp Messy error.
18
Copying Objects with Dynamic Arrays(Skip) Deep Copying Create a new array and copy contents to the array messageFixed.cpp copyFrom function fixes
19
Overload ==(Skip) To make sure no problems happen, overload == Do deep copy when an assignment is done.
20
Copy Constructor(Skip) 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
21
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.