SlideShare a Scribd company logo
ARRAYS AND
POINTERS
Michael Heron
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’
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];
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.
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.
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!
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;
Arrays of Pointers
Car **myCars;
myCars = new Car*[100];
for (int i = 0; i < 100; i++) {
myCars[i] = new Car(100.0, "Blue");
}
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!
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);
};
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.
Constructor Code
// Zero parameter
Car::Car() :
price (200.0), colour ("black"), owners (NULL), max_size (0),
current_size (0) {
}
// Two parameter
Car::Car(float p, string c) :
price (p), colour (c), owners (NULL), max_size (0), current_size (0) {
}
// Three parameter
Car::Car (float p, string c, int max) :
price (p), colour (c), owners (new string[max]), max_size (max),
current_size (0) {
}
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.
Adding and Querying
void 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];
}
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 ~.
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.
Destroying The Object
Declaration:
class Car {
private:
// Stuff
public:
Car();
Car (float, string = "bright green");
Car (float, string = "bright green", int = 20);
~Car();
// Stuff
};
Body:
Car::~Car() {
delete [] owners;
}
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.
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.

More Related Content

What's hot

Session 4
Session 4Session 4
Unit v
Unit vUnit v
Structures in c language
Structures in c languageStructures in c language
Structures in c language
tanmaymodi4
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
2 arrays
2   arrays2   arrays
2 arrays
trixiacruz
 
Array C programming
Array C programmingArray C programming
Array C programming
Prionto Abdullah
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
Fatima Kate Tanay
 
Arrays in c language
Arrays in c languageArrays in c language
Arrays in c language
tanmaymodi4
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
Mohammad Imam Hossain
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
Ashim Lamichhane
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
Jasleen Kaur (Chandigarh University)
 
Presentation of c 1
Presentation of c 1Presentation of c 1
Presentation of c 1
Love preet
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
tanmaymodi4
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Janpreet Singh
 
Arrays in c_language
Arrays in c_language Arrays in c_language
Arrays in c_language
Infinity Tech Solutions
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
Array
ArrayArray

What's hot (18)

Session 4
Session 4Session 4
Session 4
 
Unit v
Unit vUnit v
Unit v
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
2 arrays
2   arrays2   arrays
2 arrays
 
Array C programming
Array C programmingArray C programming
Array C programming
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Arrays in c language
Arrays in c languageArrays in c language
Arrays in c language
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
Arrays
ArraysArrays
Arrays
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
Presentation of c 1
Presentation of c 1Presentation of c 1
Presentation of c 1
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays in c_language
Arrays in c_language Arrays in c_language
Arrays in c_language
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Array
ArrayArray
Array
 

Viewers also liked

10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer
웅식 전
 
Arrays and pointers
Arrays and pointersArrays and pointers
Arrays and pointers
Kevin Nguyen
 
Pointers in C
Pointers in CPointers in C
Pointers in C
guestdc3f16
 
Pointers
PointersPointers
Pointers
sarith divakar
 
More Pointers and Arrays
More Pointers and ArraysMore Pointers and Arrays
More Pointers and Arrays
emartinez.romero
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classes
Docent Education
 
Multi level hierarchy
Multi level hierarchyMulti level hierarchy
Multi level hierarchy
myrajendra
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Marlom46
 
Some Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented MethodologySome Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented Methodology
Manoj Kumar
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 
Object oriented methodology & unified modeling language
Object oriented methodology & unified modeling languageObject oriented methodology & unified modeling language
Object oriented methodology & unified modeling language
Ismail El Gayar
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Multiple Inheritance For C++
Multiple Inheritance For C++Multiple Inheritance For C++
Multiple Inheritance For C++
elliando dias
 
Inheritance
InheritanceInheritance
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
daxesh chauhan
 

Viewers also liked (20)

10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer
 
Arrays and pointers
Arrays and pointersArrays and pointers
Arrays and pointers
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers
PointersPointers
Pointers
 
More Pointers and Arrays
More Pointers and ArraysMore Pointers and Arrays
More Pointers and Arrays
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classes
 
Multi level hierarchy
Multi level hierarchyMulti level hierarchy
Multi level hierarchy
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Some Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented MethodologySome Basic Concepts of Object Oriented Methodology
Some Basic Concepts of Object Oriented Methodology
 
Friend functions
Friend functions Friend functions
Friend functions
 
Object oriented methodology & unified modeling language
Object oriented methodology & unified modeling languageObject oriented methodology & unified modeling language
Object oriented methodology & unified modeling language
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Templates
TemplatesTemplates
Templates
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Multiple Inheritance For C++
Multiple Inheritance For C++Multiple Inheritance For C++
Multiple Inheritance For C++
 
Inheritance
InheritanceInheritance
Inheritance
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 

Similar to 2CPP06 - Arrays and Pointers

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
Michael Heron
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
Michael Heron
 
Aspdot
AspdotAspdot
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
AshrithaRokkam
 
7array in c#
7array in c#7array in c#
7array in c#
Sireesh K
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
Michael Heron
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
Michael Heron
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
Fisnik Doko
 
4.ArraysInC.pdf
4.ArraysInC.pdf4.ArraysInC.pdf
4.ArraysInC.pdf
FarHanWasif1
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)
Rajat Pratap Singh
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
Blue Elephant Consulting
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
David Rodenas
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learning
ASIT Education
 
C#2
C#2C#2
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
Michael Heron
 

Similar to 2CPP06 - Arrays and Pointers (20)

2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
 
Aspdot
AspdotAspdot
Aspdot
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
7array in c#
7array in c#7array in c#
7array in c#
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
4.ArraysInC.pdf
4.ArraysInC.pdf4.ArraysInC.pdf
4.ArraysInC.pdf
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learning
 
C#2
C#2C#2
C#2
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
 

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
Michael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
Michael Heron
 

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Recently uploaded

socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 

Recently uploaded (20)

socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 

2CPP06 - Arrays and Pointers

  • 2. 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’
  • 3. 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];
  • 4. 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.
  • 5. 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.
  • 6. 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!
  • 7. 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;
  • 8. Arrays of Pointers Car **myCars; myCars = new Car*[100]; for (int i = 0; i < 100; i++) { myCars[i] = new Car(100.0, "Blue"); }
  • 9. 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!
  • 10. 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); };
  • 11. 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.
  • 12. Constructor Code // Zero parameter Car::Car() : price (200.0), colour ("black"), owners (NULL), max_size (0), current_size (0) { } // Two parameter Car::Car(float p, string c) : price (p), colour (c), owners (NULL), max_size (0), current_size (0) { } // Three parameter Car::Car (float p, string c, int max) : price (p), colour (c), owners (new string[max]), max_size (max), current_size (0) { }
  • 13. 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.
  • 14. Adding and Querying void 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]; }
  • 15. 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 ~.
  • 16. 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.
  • 17. Destroying The Object Declaration: class Car { private: // Stuff public: Car(); Car (float, string = "bright green"); Car (float, string = "bright green", int = 20); ~Car(); // Stuff }; Body: Car::~Car() { delete [] owners; }
  • 18. 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.
  • 19. 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.