Lecture 7 Arrays, Dynamic Arrays & Copy Constructors “Absolute C++”

Slides:



Advertisements
Similar presentations
Kernighan/Ritchie: Kelley/Pohl:
Advertisements

Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Lecture 12 Destructors “Absolute C++” Chapters 10.3, 15.2.
Pointers “Absolute C++” Section 10.1
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Pointer Data Type and Pointer Variables
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
February 11, 2005 More Pointers Dynamic Memory Allocation.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Pointers OVERVIEW.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Review 1 List Data Structure List operations List Implementation Array Linked List.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Data Structures in C++ Pointers & Dynamic Arrays Shinta P.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
Pointers and Dynamic Memory Allocation
Yan Shi CS/SE 2630 Lecture Notes
C++ Review Data Structures.
Pointers and Dynamic Arrays
CSE 374 Programming Concepts & Tools
Standard Version of Starting Out with C++, 4th Edition
Arrays Low level collections.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Motivation and Overview
Pointer Data Type and Pointer Variables II
Pointers Revisited What is variable address, name, value?
CSCE 210 Data Structures and Algorithms
Pointers and References
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
Chapter 9: Pointers.
Dynamic Memory Allocation
Arrays in Java What, why and how Copyright Curt Hill.
7 Arrays.
9-10 Classes: A Deeper Look.
Arrays Arrays A few types Structures of related data items
Data Structures & Algorithms
Pointers and dynamic objects
COP 3330 Object-oriented Programming in C++
Standard Version of Starting Out with C++, 4th Edition
Pointers and References
ENERGY 211 / CME 211 Lecture 10 October 13, 2008.
Miscellaneous Topics I
Pointers, Dynamic Data, and Reference Types
Lecture 3 More on Flow Control, More on Functions,
9-10 Classes: A Deeper Look.
SPL – PS2 C++ Memory Handling.
Introduction to Pointers
Presentation transcript:

Lecture 7 Arrays, Dynamic Arrays & Copy Constructors “Absolute C++” Sections 5.1 - 5.3, 10.2

Arrays What is an Array? An array is a “chunk” of memory which contains consecutive instances of a given data type. Think of it as a “list” of data, each data item of the same data type. An array is declared by declaring a variable of a given type and then suffixing the declaration with a [n] where n is the number of elements you want in your array. int iArray[8]; // declares an 8 element array At this point, iArray might look like this (in memory): iArray ?? ?? ?? ?? ?? ?? ?? ?? Memory is allocated, but not initialized (hence the ??’s)

Accessing Array Elements To get at the contents of one of the array elements… Take the variable used to declare the array and suffix it with a left square bracket, the element number you wish to retrieve, followed by a right square bracket. This expression will evaluate to the value in the array at the specified index. The first index is at item 0, not 1. WARNING! C++ does no bounds checking on array accesses. Let’s take a look... int iArray[8]; // declares an 8 element array for (int k=0; k<8; k++) // arbitrary initialization iArray[k] = k; iArray 00 01 02 03 04 05 06 07

Pointers in Array Declarations What’s the difference between... int *j[4]; int (*p)[4]; The first declaration is an array of 4 pointers to int j int int int int The second is a pointer to an array of 4 integers p int int int int

Static Initialization You can assign values to an array immediately right where they are declared... int smallPrimes[7] = {2,3,5,7,11,13,17}; The same can be done for a multiple dimension array: int d[2][3] = {{0,1}, {1,0}, {1,1}}; Let’s see it in action...

Demonstration #1 Basic Arrays

Pointers and Arrays Pointers and Arrays seem very closely related Both seem to deal with accessing “chunks” of memory Yet they both seem to be geared towards different tasks Arrays are used for creating a list of elements of fixed length Pointers are used for dynamically allocating data structures at runtime Well, in C++ an array is really just a pointer. Consider the following... int main() { int *a, b[8] = {1,2,3,4,5,6,7,8}; a = b; cout << “*a is “ << *a << endl; } What will be printed out as the value of *a?

Pointers and Arrays (cont) To better understand, consider a graphical representation of b: b 01 02 03 04 05 06 07 08 Now, since an array is a pointer, b actually points at its first element. That means that for any array, the following is true: int main() { int b[8] = {1,2,3,4,5,6,7,8}; if (b == &b[0]) cout << “This will always be true.” return 0; }

Sanity Check (Arrays as Pointers) Demonstration #2 Sanity Check (Arrays as Pointers)

Pointer Arithmetic You might be wondering… Yes. If *b is the same as b[0] can I access other elements of b without using [n] notation? Yes. Actually, for any array p : p[n] == *(p+n) This is called pointer arithmetic To add to the confusion, p[n] == n[p] (because *(p+n) == *(n+p)) So... int main() { int b[8] = {1,2,3,4,5,6,7,8}; cout << “b[1] = “ << b[1] << endl; // Prints out b[1] cout << “b[2] = “ << 2[b] << endl; // Prints out b[2] cout << “b[3] = “ << *(b+3) << endl; // Prints out b[3] return 0; }

Back to Arrays… Let’s check it out... Since every array is a pointer, what do you suppose this does... void swap(int A[8], int j, int k) { int temp = A[j]; A[j] = A[k]; A[k] = temp; } int main() int b[8] = {1,2,3,4,5,6,7,8}; swap(b,2,3); cout << “b[2]=“ << b[2] << “ and b[3]=“ << b[3] << endl; return 0; Let’s check it out...

Pointers as Parameters Demonstration #3 Pointers as Parameters

Pointers as Parameters Since every array is passed by pointer it has the same effect as being “passed by reference”. Remember, C++ does no bounds checking. int main() { int a1[8]; int a2[20]; int a3[5]; swap(a1,2,7); // a1 is the right size swap(a2,2,7); // a2 is too big swap(a3,2,7); // a3 is too small, there’s no a3[7] } These are all “legal”… Why? Remember, an array is just a pointer. That’s why.

Dynamic Allocation of Arrays Yes, an array can be dynamically allocated. But you won’t use: int a1[8] = new int; // WRONG! Remember, when you use the [n] notation in a declaration you are actually allocating memory at that point. Remember also that an array is just a pointer. When dynamically allocating space for an array, you will be receiving a pointer back... int *a = new int[8]; // RIGHT! The [8] tells the new operator to allocate an array of 8 ints. How do you delete such a dynamic allocation? delete [] a; // Must use this, delete a is undefined

Dynamic Allocation of Arrays (cont) What’s nice about this method of dynamic allocation is that the size of the array does not need to be known at compile time. Consider the following: int main() { Course *courses; int numCourses; cout << “How many courses to enter? “; cin >> numCourses; courses = new Course[numCourses]; // Rest of program delete [] courses; } Let’s see this actually work...

Dynamic Allocation of Arrays Demonstration #4 Dynamic Allocation of Arrays

That Nasty Scope Thing Again As always, there are dangers... int *MakeArray() // Will compile, but I wouldn’t advise it { int iArray[50]; return iArray; } int *MakeArray(int size) // Will compile, and is safe int *anArray = new int[size]; if (anArray == NULL) cout << “Couldn’t allocate array of size “ << size << endl; return anArray;

Copy Constructors Consider a constructor which takes an object of same type class Point { public: Point(){} Point(Point anotherPoint); void setXY(int newX,int newY) {x =newX; y=newY; } void getXY(int &curX,int &curY) {curX=x; curY = y; } private: int x,y; }; Point::Point(Point anotherPoint) anotherPoint.getXY(x,y); }

Copy Constructors (cont) In a pass by value situation you are actually creating a copy of a given argument on the stack. If the argument is a class and has a constructor, it will be called. If the parameter to the “copy constructor” is declared pass by value, it will be called You can see this would produce infinite recursion! Thus, for a copy constructor, the argument must be passed by reference.

Lecture 7 Final Thoughts