Lecture on pointers, references, and arrays and vectors

Similar documents
THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Exercise 1.1 Hello world

Function Templates. Consider the following function:

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

1. Which of the following best describes the situation after Line 1 has been executed?

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Computer Programming

Linked lists Tutorial 5b

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

C++ for Java Programmers

CS24 Week 3 Lecture 1

Fast Introduction to Object Oriented Programming and C++

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Chapter 1: Object-Oriented Programming Using C++

Dynamic Memory Allocation

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

C++ Scope Resolution Operator ::

Informatik I (D-ITET) Übungsstunde 9, Hossein Shafagh

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Lab Instructor : Jean Lai

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Topics. bool and string types input/output library functions comments memory allocation templates classes

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

W3101: Programming Languages C++ Ramana Isukapalli

Introduction to C++ Introduction to C++ 1

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

Templates and Vectors

Suppose that you want to use two libraries with a bunch of useful classes and functions, but some names collide:

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

Variables, Memory and Pointers

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

BITG 1113: Function (Part 2) LECTURE 5

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Lecture 23: Pointer Arithmetic

CSI33 Data Structures

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

CS

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

C++ For Science and Engineering Lecture 2

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Programming in C/C Lecture 2

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

PENN STATE UNIVERSITY Department of Economics

Exercise 9 Pointers, Iterators and Recursion

Intermediate Programming, Spring 2017*

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

CMSC 202 Midterm Exam 1 Fall 2015

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

pointers + memory double x; string a; int x; main overhead int y; main overhead

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

C++ For Science and Engineering Lecture 15

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS 240 Data Structure Spring 2018 Exam I 03/01/2018

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

CS2141 Software Development using C/C++ C++ Basics

BITG 1113: POINTER LECTURE 12

2 nd Week Lecture Notes

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

1. The term STL stands for?

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Dynamic Allocation of Memory

9. Arrays. Compound Data Types: type name [elements]; int billy [5];

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Containers in C++ and Java

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

C++ Structures Programming Workshop 2 (CSCI 1061U)

UEE1303(1070) S12: Object-Oriented Programming Advanced Topics of Class

ECE 462 Exam 1. 6:30-7:30PM, September 22, 2010

Pointers and Strings. Adhi Harmoko S, M.Komp

G52CPP C++ Programming Lecture 18

Type Conversion. and. Statements

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

C Pointers. 6th April 2017 Giulio Picierro

Exam 3 Chapters 7 & 9

Reference operator (&)

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

1 Short Answer (5 Points Each)

Pointers and Strings Prentice Hall, Inc. All rights reserved.

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

This is a CLOSED-BOOK-CLOSED-NOTES exam consisting of five (5) questions. Write your answer in the answer booklet provided. 1. OO concepts (5 points)

Bruce Merry. IOI Training Dec 2013

CS 103 Unit 13 Slides

C++ Lecture 5 Arrays. CSci 588: Data Structures, Algorithms and Software Design.

CS93SI Handout 04 Spring 2006 Apr Review Answers

CSCE Practice Midterm. Data Types

Transcription:

Lecture on pointers, references, and arrays and vectors pointers for example, check out: http://www.programiz.com/cpp-programming/pointers [the following text is an excerpt of this website] #include <iostream> using namespace std; int main() { int var1 = 3; int var2 = 24; int var3 = 17; cout << &var1 << endl; cout << &var2 << endl; cout << &var3 << endl; Output 0x7fff5fbff8ac 0x7fff5fbff8a8 0x7fff5fbff8a4 Example if Pointer values and pointer dereferencing:

#include <iostream> using namespace std; int main() { int *pc int c; c = 5; cout << "Address of c (&c): " << &c << endl; cout << "Value of c (c): " << c << endl << endl; pc = &c; // Pointer pc holds the memory address of variable c cout << "Address that pointer pc holds (pc): "<< pc << endl; cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl; c = 11; // The content inside memory address &c is changed from 5 to 11. cout << "Address pointer pc holds (pc): " << pc << endl; cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl; *pc = 2; cout << "Address of c (&c): " << &c << endl; cout << "Value of c (c): " << c << endl << endl; return 0; Output Address of c (&c): 0x7fff5fbff80c Value of c (c): 5 Address that pointer pc holds (pc): 0x7fff5fbff80c Content of the address pointer pc holds (*pc): 5 Address pointer pc holds (pc): 0x7fff5fbff80c Content of the address pointer pc holds (*pc): 11 Address of c (&c): 0x7fff5fbff80c Value of c (c): 2 C++ References vs Pointers References are often confused with pointers but three major differences between references and pointers are:

You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time. We declare a variable int i = 17; We can now declare reference variables for i as follows. int& r = i; Read the & in these declarations as reference. Thus, read the first declaration as r is an integer reference initialized to i and read the second declaration as s is a double reference initialized to d.. Following example makes use of references on int and double: #include <iostream> using namespace std; int main () { // declare simple variables int i; double d; // declare reference variables int& r = i; double& s = d; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl; return 0;

When the above code is compiled together and executed, it produces the following result: Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7 References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer: Concept References as parameters Reference as return value Description C++ supports passing references as function parameter more safely than parameters. You can return reference from a C++ function like a any other data type can be returned. References and Pointers comparison:

#include <iostream> // using references void swapref(int &a, int &b) { int temp = 0; temp = a; a = b; b = temp; return; // using Pointers void swappoint(int *a, int *b){ int temp = 0; temp = *a; *a = *b; *b = temp; return; // example of using pointers or references // result is the same int main(void){ int a = 10; int b = 20; std::cout<< "a = "<< a <<"\n"<<"b = "<<b<<"\n"; swapref(a,b); std::cout<< "After swapref()"; std::cout<< "a = "<< a <<"\n"<<"b = "<<b<<"\n"; a = 10; b = 20; swappoint(&a,&b); std::cout<< "After swappoint()"; std::cout<< "a = "<< a <<"\n"<<"b = "<<b<<"\n"; return 0; To const or not to const [see http://duramecho.com/computerinformation/whyhowcppconst.html] There are many uses and usages of const [it means stay constant do not change] An obvious example:

const int a= 5; cout << a << endl; a = 6; // <== this will not compile! ERROR! You shalt not change a You can use const for pointers, but there are a few difficulties: const int * p; int const * q; int * const r; int const * const s; Confusing, right? Here the explanation. const int * p; Declares that p is a variable pointer to a const integer. For example const int a=5; const int *p; p = NULL; // p points to nothing p = &a; // p points to a in fact on a mac this seems to be equivalent to int * p and is also equivalent to int const * q and also int * const r sugggests to have a constant pointer to a variable integer, ti seems that on mac all these lead to the same answers and also compile. The only difference is int const * const s; it is a const pointer to a const value; this only compiles using something like this: const int a=5; int const * const p = &a; You can protect return values of function against change using const char *function() { return "Some text"; You can use const in arguments, here it becomes difficult: For example:

void addone(int a) { a = a + 1; int a = 5; addone(a); // a does not change makes a copy of a and then adds one, but the results gets lost. We can use a reference: void addone(int &a) { a = a + 1; int a = 5; addone(a) cout << a << endl; //prints 6 Now a gets changed, if we do not want that a gets changed then we can use const void addone(const int &a) { a = a + 1; /COMPILER ERROR This forces us to make sure that we do not manipulate objects that should be left alone. Within classes we can add const after method definition to make sure that the method cannot change the class object it self. class Class2 { void Method1() const; int Membervariable1; For example we have encountered this in the operator methods: Look at our definition of operator+, correctly we would want to make sure that an operation a+b does not change or b const Rectangle Rectangle::operator+(const Rectangle &other) const { Rectangle newr = *this; newr.side = side + rhs.side; newr.height = height + rhs.height; return newr; Arrays we know about double a; a = 5;

if we want to get a list of values and use them more like we know from math then we can define an array double a[10]; for (int i=0;i<10;i++) { a[i] = 5+i; or easier: int a[3] = {4,5,6; or even easier: int a[] = {4,5,6,7; We can also define 2D-arrays: int b[2][3] = {{1,2,3,{4,5,6; But what about dynamic arrays, the ones above are fixed length. Allocation of memory on the fly Use the keywords new and delete. int * myarray = new int[size] //gives you a contigous memory block once your done with it you MUST delete it: delete [] myarray; if you use new to allocate for a single memory cell int * a = new double; //then you need this to delete: delete a; if you use new to allocate multiple memory cells

int * a = new double[size]; //then you need this to delete: delete [] a; Now this is all very combersome, and you should probably not use your own arrays or Array classes. Standard Template Library (STL) Vector class is an example of the STL

#include <iostream> #include <vector> using namespace std; int main() { // create a vector to store int vector<int> vec; int i; // display the original size of vec cout << "vector size = " << vec.size() << endl; // push 5 values into the vector for(i = 0; i < 5; i++){ vec.push_back(i); // display extended size of vec cout << "extended vector size = " << vec.size() << endl; // access 5 values from the vector for(i = 0; i < 5; i++){ cout << "value of vec [" << i << "] = " << vec[i] << endl; // use iterator to access the values vector<int>::iterator v = vec.begin(); while( v!= vec.end()) { cout << "value of v = " << *v << endl; v++; return 0;