PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Similar documents
a data type is Types

PIC 10A Objects/Classes

Pointers, Dynamic Data, and Reference Types

Tokens, Expressions and Control Structures

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2. Procedural Programming

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Pointers and References

In Java we have the keyword null, which is the value of an uninitialized reference type

Short Notes of CS201

[0569] p 0318 garbage

CS201 - Introduction to Programming Glossary By

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

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

A First Program - Greeting.cpp

Vector and Free Store (Pointers and Memory Allocation)

Reference operator (&)

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointers and Memory 1

The C++ Language. Arizona State University 1

Do not turn to the next page until the start of the exam.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Pointers. Reference operator (&) ted = &andy;

Object-Oriented Programming for Scientific Computing

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

LECTURE 02 INTRODUCTION TO C++

Pointers II. Class 31

Chapter 2: Introduction to C++

These are notes for the third lecture; if statements and loops.

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

CS 11 C track: lecture 5

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Memory, Data, & Addressing II CSE 351 Spring

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

CSI33 Data Structures

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Chapter 2 Basic Elements of C++

Documentation. Programming / Documentation Slide 42

A brief introduction to C programming for Java programmers

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

UNIT- 3 Introduction to C++

6. Pointers, Structs, and Arrays. 1. Juli 2011

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Pointers, Arrays and C-Strings

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Chapter 17 vector and Free Store. Bjarne Stroustrup

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

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

Variables. Data Types.

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Integer Data Types. Data Type. Data Types. int, short int, long int

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

CMSC 202 Midterm Exam 1 Fall 2015

Class Information ANNOUCEMENTS

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

CS 222: Pointers and Manual Memory Management

Fundamentals of Programming CS-110. Lecture 2

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

Basic Types, Variables, Literals, Constants

C++ for Java Programmers

Intermediate Programming, Spring 2017*

Variables and Constants

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

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

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

Outline. 1 About the course

CPSC 427: Object-Oriented Programming

Input And Output of C++

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

CS201- Introduction to Programming Current Quizzes

W3101: Programming Languages C++ Ramana Isukapalli

Programming, numerics and optimization

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

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

Dynamic Data Structures. CSCI 112: Programming in C

Pointers and Dynamic Memory Allocation

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

QUIZ. What is wrong with this code that uses default arguments?

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Pointers in C/C++ 1 Memory Addresses 2

1d: tests knowing about bitwise fields and union/struct differences.

Objectives. In this chapter, you will:

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.

Heap Arrays and Linked Lists. Steven R. Bagley

Homework #3 CS2255 Fall 2012

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

Chapter 17 vector and Free Store

12. Pointers Address-of operator (&)

Transcription:

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics

Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable. double d = 0.1 ; double * d_p = &d; cout << d_p << endl ; The output happens to be 008FF780. 2

Pointers double * d_p ; d_p is a variable of type double* (read as double pointer ). Or we say d_p a pointer to a double. double * d_p = &d; &d returns the address of d, and it is of type double*. cout << d_p << endl ; This outputs the memory address at which d is stored. A double is 8 bytes. So the memory addresses 008FF780, 008FF781,..., 008FF787 are used to store d. 3

Pointers The indirection or dereference operator * allows us to access the variable a pointer is pointing to. double d = 0.1 ; double * d_p = &d; cout << * d_p << endl ; * d_p = 3.0 ; cout << d << endl ; The output is 0.1 and 3.0. *d_p returns the double of value 0.1. *d_p = 3.0; assigns 3.0 to the double at location d_p. You now know 3 separate uses for the symbol *: multiplication, dereferencing, and defining a pointer. 4

sizeof operator sizeof returns the number of bytes it takes to store a variable. cout << sizeof ( int ) << endl ; cout << sizeof ( double ) << endl ; The output (on my machine) is 4 and 8. 5

Arrays An array is a sequence of variables. int ages [10 ]; for ( int i=1; i <= 10; i ++) { int thisage ; cout << " Student number " << i <<" has age : "; cin >> thisage ; ages [i-1] = thisage ; //0- based indexnig } cout << " The ages are " << endl ; for ( int i=0; i<10; i ++) cout << ages [i] << endl ; (Elements of an array is accessed with 0-based indexing.) 6

Arrays are pointers Actually arrays are (almost) pointers! int ages [10 ]; int * int_ p = ages ; // ages is of type int * for ( int i=1; i <= 10; i ++) {... // Initialize ages [ ] } cout << ages << endl ; cout << int_ p << endl ; for ( int i=0; i<10; i ++) cout << int_ p [ i] << endl ; // You can do this int_p and ages are the same. 7

Arrays are pointers Since ages is of type int*, it points to a memory address at which an integer is stored. int ages [10 ]; for ( int i=1; i <= 10; i ++) {... // Initialize ages [ ] } cout << ages << endl ; The output is the address of ages[0]. 8

The memory layout of an array 9

Pointer arithmetic You can do basic arithmetic with pointers. Since sizeof(int) is 4, int_p+1 points to the address 4 bytes away from int_p cout << int_ p << endl ; cout << ( int_p +1) << endl ; The output happens to be 00F3FC64 and 00F3FC68. 10

Arrays are pointers We can also access an array with pointer arithmetic (as opposed to using []). for ( int i=0; i<10; i ++) cout << ages [i] << endl ; for ( int i=0; i<10; i ++) cout << *( ages + i) << endl ; for ( int * iter = ages ; iter <( ages +10 ); iter ++) cout << * iter << endl ; These 3 for loops have the same output. 11

Array initialization We can declare and initialize a variable in one statement using an initializer list. double d = 0.3 ; We can do the same with arrays. // w has length 3 and holds 1,2,3 int w[] = {1,2,3}; // x has length 5 and holds 1,2,3000,0,0 float x[5] = {1.f,2.f,3 E3f }; // y has length 3 and holds all zeroes int y[3] = {0}; // Better style? // z has length 10 and holds all zeroes double z[10] = {}; 12

Where do variables go? Pointers reveal the physical location of variables. Where do variables go? The operating system (OS) keeps track of which patch of memory is available. When the C++ program declares a variable, it asks the OS for memory. Which patch of memory you get depends on what part of the memory is available, which in turns depends on the what other programs are running and the current state of the OS. Arrays are placed on a contiguous patch of memory. This has to be true for pointer arithmetic to work. 13

Type conversion Type conversion or type casting is the conversion of a variable of one type to another. double d1 = 3; 3 is a literal of type int, and it is (implicitly) converted/casted into a double. There are explicit and implicit conversions. 14

Type conversion: explicit Explicitly convert T1 T2. C-style cast: (T2) T1. float f = ( float ) 3; // cast int to float double d = ( double ) f; // cast float to double // cast 1 and 3 into double before division cout << (( double ) 1) / (( double ) 3) << endl ; 15

Type conversion: explicit Explicitly convert T1 T2. Functional cast or function style cast: T2(T1). int i = 2000000000 ; // i = 2 billion cout << 10 * i << endl ; cout << 10 *( long long int ( i) ) << endl ; The output is -1474836480 and 20000000000. 16

Type conversion: explicit Explicitly convert T1 T2. Static cast: static_cast<t2>(t1). bool b1 = static_cast <bool >(0); bool b2 = static_cast <bool >(3); cout << b1 << endl ; cout << b2 << endl ; The output is 0 and 1. We will later discuss where the names C-style cast and functional cast come from. 17

Type conversion: explicit Upon encountering these casts, the compiler will attempt to carry them out. If there is no a suitable way, the cast will fail (i.e., your code won t compile). int i = 3; string s1 = static_cast < string >(i); // Error! We ll later learn what a suitable way of conversion means. 18

Type conversion: implicit Implicit conversion from type T1 to type T2 is attempted when type T1 is used where type T2 is expected. double d = 5; // Implicit cast from int to double int i = 3; float f = i; // Implicit cast from int to float 19

Type conversion: which one? Which cast should you use? Ordered in verbosity: static < functional = C-style < implicit. Ordered in readability (subjective): funcational > static > implicit > C-style. Ordered in safety: static > functional = C-style > implicit. Static cast is safe because it is conspicuous in that is is more visible and in that you can easily search (with ctrl+f) to find it. (There s one more subtle reason that s beyond the scope of this class.) In my opinion, the functional cast is always better than the C-style cast. Otherwise, handle the trade-off on a case-by-case basis. 20

typeid Use typeid to check what type your object is. # include < iostream > # include < typeinfo > using namespace std ; int main () { int i = 5; long long int j = 2; cout << typeid ( i). name () << endl << typeid (j). name () << endl << typeid (i+j). name () << endl ; } Output is int, int64, and int64. 21

The type char The type char (short for character) is a fundamental type. sizeof(char) equals 1. A literal of type char is written as a single character in single quotes. char c1 = a ; cout << c1 << endl ; 22

The type char A char can take on 256 possible values. (Why 256?) The ASCII standard (American Standard Code for Information Interchange) specifies which value corresponds to which character. http://www.asciitable.com/ # include < iostream > # include < bitset > using namespace std ; int main () { char c = char (65 ); cout << c << endl ; bitset <8> x(c); cout << x << endl ; // see the bits stored in & c } The output is A and 01000001. 23

Arithmetic with char We also can view char as an integer type with a value range of 128 to 127. You can (implicitly) cast a char into an int and perform arithmetic. char c; while ( true ) { cout << " Enter a lower case letter " << endl ; cin >> c; cout << "We capitalized it: " << char (c-0 x20 ) << endl ; cout << typeid (c-0 x20 ). name () << endl ; // int } 0x20 is a literal of type int written in hex. 0x or 0X means hex. In c-0x20, we have a char minus an int. So c, a char, is implicitly converted into an int to perform the arithmetic. char(c-0x20) converts the int back to a char. 24

Relational operators with char The comparison operators are quite useful. char c; cout << " Input a letter " << endl ; cin >> c; if ( a <=c && c <= z ) cout << " Input is lower case " << endl ; else if ( A <=c && c <= Z ) cout << " Input is upper case " << endl ; else if ( 0 <=c && c <= 9 ) cout << " Input is a number " << endl ; else if ( <= c && c <= ~ ) cout << " Input is a special character " << endl ; else cout << " Input is something else " << endl ; 25

char array A char array is more than just a sequence of chars. In programming, a string is a sequence of characters. In C++ there are 2 common ways to represent a string: with type string and with a char array. A C-style string is a char array terminated by the null character, written as \0 or char(0). strings are better than C-style strings, but you must know both. 26

char array initialization char arrays are special in that they have an additional way to initialize. char s1 [] = { H, e, l, l, o, \0 }; char s2 [] = " Hello "; // special syntax char s3 [] = { H, e, l, l, o }; s1 and s2, valid c-strings, are char arrays of size 6. s3, not a valid c-string, is of size 5. 27

char array initialization The normal initializer list syntax works with char arrays. char s1[5] = { a, b }; char s2[5] = { a, b, \0, \0, \0 }; cout << int (s1[2]) << endl ; The output is 0. s1 and s2 are the same valid C-style strings. 28

cout treats char arrays specially. char array cout int i_a [] = {1,2,3}; char s1 [] = { H, e, l, l, o, \0 }; char s2 [] = " Hello "; // special syntax char s3 [] = { H, e, l, l, o }; cout << i_a << endl ; // pointer address cout << s1 << endl ; // Hello cout << s2 << endl ; // Hello cout << s3 << endl ; // Fail Instead of printing the address s1, cout performs something like for ( int i=0; s1[i ]!= \0 ; i ++) cout << s1[i]; cout << endl ; So cout needs the terminating null character to know when to stop. 29

C-string literals "Hello" isn t a literal of type string. It s actually a literal of type const char array. cout << typeid (" Hello "). name () << endl ; const char * s = " Hello "; cout << s << endl ; When we assign a C-string literal to a string, implicit type casting happens. // string s = " Hello world "; // the same as string s = static_ cast < string >(" Hello world "); 30

Limitations of arrays (on the stack) The length of the array must be a constant (i.e., specified in the code). int n; cin >> n; double d[n]; // Error Using const int doesn t solve the problem. int n; cin >> n; const int m = n; double d[m]; // Error These arrays can t be too large. int arr [ 1000000 ]; // Error 1,000,000 ints occupy merely 4 megabytes. 31

Stack vs. heap Within memory, there is the stack and the heap. The stack is small but fast (for reasons beyond the scope of this class). The variable and array definitions we ve seen so far place the variables on the stack. These are also called local or automatic variables. The heap, also called dynamic memory, is large but slower (but still fast compared to secondary storage). We will learn dynamic memory allocation, which places variables on the heap. In C++, the opposite of dynamic variables isn t static variables. Static variables mean something else unrelated to the stack. 32

Dynamic allocation Use the new operator to declare a variable on the heap. double * d_p = new double ; new T creates a variable of type T and returns a pointer pointing to it. Variables on the stack don t use new. double d = 0.0 ; 33

delete operator You must deallocate a dynamically allocated variable with the delete operator when you re done with it. In other words, you must free the memory when you re done with it. double * d_p = new double ;... // code using d_p ; delete d_p ; The deallocation tells the OS that we re no longer using the memory address. Variables on the stack are deallocated automatically when they go out of scope. 34

Dynamic arrays Use new T[n] to declare an array of type T of length n on the heap. int n; cin >> n; double * d_a = new double [ n]; delete [] d_a ; You must use delete[] to deallocate a dynamic array. Don t use delete[x]. Don t use delete. Use delete[]. 35

Dynamic arrays Advantages of dynamic arrays over local arrays: Array length does not have to be predetermined. Array can be large enough to hold gigabytes. # include < iostream > using namespace std ; int main () { int n; cin >> n; char * c_a = new char [n]; cout << " wait a second "; char c; cin >> c; // check the memory monitor delete [] c_a ; cout << " memory has been freed "; cin >> c; } 36

Memory leak When you don t free memory you allocate, the memory is leaked and becomes unavailable until the end of the program. (The OS reclaims the memory when the program is done.) int main () { int count = 0; while ( true ) { char * c_p ; c_p = new char [ 1000000 ]; count ++; cout << count << " Mbytes of memory leaked.\ n"; } } Memory leaks are one of the worst kinds of bugs! They are very hard to track down as they often do no immediate harm. However, they can lead your program to run out of memory and crash over time. 37

Arrays vs. pointers Actually, there is a small difference between an array and a pointer. Write T [] for an array of type T. int main () { int * n; int m[2]; int * k = new int [10 ]; cout << typeid (n). name () << \n ; cout << typeid (m). name () << \n ; cout << typeid (k). name () << \n ; delete [] k; } The distinction is rarely necessary. Only local arrays can have type T []. 38