19
ARRAYS AND POINTERS Michael Heron

2CPP06 - Arrays and Pointers

Embed Size (px)

DESCRIPTION

This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.

Citation preview

Page 1: 2CPP06 - Arrays and Pointers

ARRAYS AND POINTERSMichael Heron

Page 2: 2CPP06 - Arrays and Pointers

Introduction• We talked about pointers a few lectures ago.• In this lecture we are going to talk about pointers and

arrays.• This is a little bit more complicated than working with simple arrays

in Java.

• It is expected you are comfortable with the mechanics of pointers at this point.• & is the ‘address of’• * is the ‘value of’

Page 3: 2CPP06 - Arrays and Pointers

Arrays in C++• Arrays in Java have a two-step setup process.

• Declare the array object• int[] myInts

• Create the array• myInts = new int[100];

• In C++, we can use pointers to do the same two stage process.• Declare the array object

• int *myInts

• Create the Array• myInts = new Int[100];

Page 4: 2CPP06 - Arrays and Pointers

Arrays in C++• You can also declare an array in C++ in a single step:

• int myInts[100];• This doesn’t work in Java.

• Arrays in Java are fully fledged objects.• They have methods and attributes.

• C++ does not provide these for you.• You have to manually manage their state, size and such.

Page 5: 2CPP06 - Arrays and Pointers

Arrays and Pointers• When an array is created as a pointer, the pointer

reference is to the memory location of the first element in the array.• When using index accessing, the numeric index acts as an offset.

• myInts[3] means ‘get the element three spaces on from the first’

• Exciting Language Feature!• C++ doesn’t do any compile time bounds checking on arrays.

• If you set an element that is greater than the size of the array, it will write to that memory location anyway.

• Easy way for things to go weird.

Page 6: 2CPP06 - Arrays and Pointers

Arrays of Objects• Three step process in Java.

• Declare the array• Create the array of object references• Initialize each object reference.

• C++ permits this as a one stage or two stage process.• Same as creating an array of any other data type.• The compiler will create an array of objects created using the zero

parameter constructor.• Hence the importance of a zero parameter constructor!

Page 7: 2CPP06 - Arrays and Pointers

Arrays of Objects• You can simulate the Java creation process through the

use of an array of pointers.• Here’s where it gets tricky.

• First we create an array of pointers to objects.• We then initialise each pointer in that array by creating an object

for it to point.• The syntax for creating an array of pointers is double asterisks on

the declaration:• Car **myCars;

Page 8: 2CPP06 - Arrays and Pointers

Arrays of Pointers

Car **myCars;

myCars = new Car*[100];

for (int i = 0; i < 100; i++) { myCars[i] = new Car(100.0, "Blue"); }

Page 9: 2CPP06 - Arrays and Pointers

Worked Example• Let’s look at this concept by working through an example.

• We’re going to add a list of all previous owners to our car objects.

• First of all, we need to add an array of strings to our car declaration.• We also need to store the size of the array.

• C++ doesn’t do that for us.• Egads!

Page 10: 2CPP06 - Arrays and Pointers

Worked Example

class Car {private: float price; string colour; string *owners; int max_size; int current_size;

public: Car(); Car (float, string = "bright green"); void set_price (float p); float query_price(); void set_colour (string c); string query_colour(); string to_string(); int query_size(); int query_current_size(); void add_owner (string str); string query_owner (int ind);};

Page 11: 2CPP06 - Arrays and Pointers

Constructors• Our zero parameter constructor should handle the default

case.• Set the owners array to NULL• Set the max_size to 0• Set the current_size to 0.

• Also add in constructor that allow us to set a maximum size of the array.• Three parameter constructor.

Page 12: 2CPP06 - Arrays and Pointers

Constructor Code// Zero parameterCar::Car() : price (200.0), colour ("black"), owners (NULL), max_size (0), current_size (0) {}

// Two parameterCar::Car(float p, string c) : price (p), colour (c), owners (NULL), max_size (0), current_size (0) {}

// Three parameterCar::Car (float p, string c, int max) : price (p), colour (c), owners (new string[max]), max_size (max), current_size (0) {}

Page 13: 2CPP06 - Arrays and Pointers

Adding an Owner• We next need to implement the add_owner method.

• Check to see if our array is full.• If it isn’t, add the element at the right location.• Increment the counter by one.

• We need to do our own array bounds validation here.

Page 14: 2CPP06 - Arrays and Pointers

Adding and Queryingvoid Car::add_owner (string str) { if (current_size == max_size) { return; }

owners[current_size] = str; current_size += 1;}

string Car::query_owner (int location) { if (location >= max_size) { return "Invalid"; }

if (location < 0 ) { return "Invalid"; }

return owners[location];}

Page 15: 2CPP06 - Arrays and Pointers

Destroying The Object• As discussed in an earlier lecture, Java offers garbage

collection to deal with memory leaks.• C++ doesn’t.

• Whenever we destroy an object, we must also destroy any dynamically allocated memory.• Our owners array.

• We do this in the class’s destructor method.• Same name as a constructor, prefix of a ~.

Page 16: 2CPP06 - Arrays and Pointers

Destroying The Object• When using delete on an array, we include an empty pair

of square brackets:• delete [] owners;

• When deleting a pointer to a single data field, we can omit the brackets:• delete owners;

• In this case, we need the square brackets in our destructor.

Page 17: 2CPP06 - Arrays and Pointers

Destroying The ObjectDeclaration:

class Car {private: // Stuffpublic: Car(); Car (float, string = "bright green"); Car (float, string = "bright green", int = 20); ~Car(); // Stuff};

Body:

Car::~Car() { delete [] owners;}

Page 18: 2CPP06 - Arrays and Pointers

Tomorrow’s Tutorial• The tutorial tomorrow is a group exercise to write, on

paper, the code needed for a simple CD database.• Directly applicable to your assessment.

• Understanding the nature of pointers and the lifecycle of an object are important concepts for this.

• The exercise focuses on understanding.• You don’t need to be syntax perfect.

Page 19: 2CPP06 - Arrays and Pointers

Summary• Arrays in C++ differ somewhat from those provided in

Java.• They can be manipulated through pointers in the same

way that simple variable types can.• Syntax very similar to Java.

• Implications of certain actions are different.

• Additional complexity and power afforded by pointer manipulation.