CS 31 Discussion 1A, Week 8. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Similar documents
CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

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

CS 31 Discussion ABDULLAH-AL-ZUBAER IMRAN WEEK 6: C-STRINGS, STRUCT, CLASS AND PROJECT4

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

CS 31 Discussion 1A, Week 4. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

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

a data type is Types

CSC1322 Object-Oriented Programming Concepts

Pointers, Dynamic Data, and Reference Types

CMSC 202 Midterm Exam 1 Fall 2015

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):

Input And Output of C++

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

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

Fast Introduction to Object Oriented Programming and C++

CS 376b Computer Vision

C++ for Java Programmers

Review Questions for Final Exam

Kurt Schmidt. October 30, 2018

Fundamentals of Programming CS-110. Lecture 2

CS 31 Discussion 1A, Week 1. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50

Object Oriented Programming COP3330 / CGS5409

Ch. 17: Linked Lists. Introduction to Linked Lists

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

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

Object Reference and Memory Allocation. Questions:

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

CSCE 110 PROGRAMMING FUNDAMENTALS

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Pointers and References

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

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

CS 61c: Great Ideas in Computer Architecture

CS31 Discussion. Jie(Jay) Wang Week6 Nov.4

Implementing an ADT with a Class

Linked List using a Sentinel

Name. CPTR246 Spring '17 (100 total points) Exam 2

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

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

Tin học cơ sở 4$ Structures!

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

CS 103 Unit 11. Linked Lists. Mark Redekopp

Stack memory - "scratch pad" memory that is used by automatic variables.

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Lecture 12. We have already used strings. Strings. Hello Class is a string.

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

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

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

III. Classes (Chap. 3)

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:

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Arrays and Pointers. Overview. Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays

OBJECT ORIENTED PROGRAMMING

Pointers, Arrays and C-Strings

EECS402 Lecture 08. Intro To The Standard string Class. Some string Functionality

Homework #3 CS2255 Fall 2012

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

Functions, Arrays & Structs

Arrays. Week 4. Assylbek Jumagaliyev

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Assignment #1 (50 points; due 11:59 P.M.)

CS 103 Lab - Party Like A Char Star

CS2255 HOMEWORK #1 Fall 2012

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

Getting started with C++ (Part 2)

Object Oriented Design

EECS402 Lecture 02. Functions. Function Prototype

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Your First C++ Program. September 1, 2010

C++ Casts and Run-Time Type Identification

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

CS31 Discussion 1E Spring 17 : week 08

Introduction to Programming EC-105. Lecture 2

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

Friend Functions and Friend Classes

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

CS 115 Exam 3, Spring 2010

Global & Local Identifiers

EE 355 Lab 4 - Party Like A Char Star

Classes and Objects in C++

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Reference operator (&)

CS 103 Lab 6 - Party Like A Char Star

Intermediate Programming, Spring 2017*

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

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

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Structured Data. CIS 15 : Spring 2007

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Structures. Lecture 5. Structures

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Transcription:

CS 31 Discussion 1A, Week 8 Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

Today s focus Pointer Structure Clarifications

Pointer A pointer is the memory address of a variable. It provides direct access to manipulate values in memory Pointer v.s. Variable: Pointer holds memory address Variable holds some value

Pointer: love-hate relationship http://imgs.xkcd.com/comics/pointers.png

Pointer: basics Pointer variable (don t confuse with the variables!) <type> *<name>; int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character Pointer representation in memory courtesy: Andrew Forney

Pointer: important operations Most common patterns when you use pointer (a) define pointer variables (b) assign the address of a variable to a pointer (c) finally access the value at the address available in the pointer variable.

Pointer: access variable values The & and * operators get address and dereference #include <iostream> using namespace std; int main () { int var = 20; int *ip; ip = &var; // actual variable declaration. // pointer variable // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl;

Pointer: example #include <iostream> #include <string> using namespace std; int main () { int imanint = -100; int* pointy = &*&imanint; cout << *pointy << endl;

Pointer: example #include <iostream> #include <string> using namespace std; int main () { int pointedat = 1; int* pointy = &pointedat; int* ditto; // Will these 2 be equal? cout << pointy << endl; cout << ditto << endl; ditto = pointy; // Will these 2 be equal? cout << *pointy << endl; cout << *ditto << endl; // Will these 2 be equal? cout << pointy << endl; cout << ditto << endl;

Pointer: assignment operator

Pointer: null pointer Sometimes we return a null pointer (e.g. to indicate an error) Two flavors: NULL a constant, 0. nullptr introduced in C++11. A literal constant.

Pointer: null pointer example double* findfirstnegative(double a[], int n) { for (double* p = a; p < a + n; p++) { if (*p < 0) return p; return nullptr;... double* p = findfirstnegative(da, 5); if (p == nullptr)... else...

Pointer: null pointer example #include <iostream> #include <string> using namespace std; int main () { int i = 50; int* latepointer = nullptr; if (latepointer == nullptr) { latepointer = &i; else { cout << "<_< >_>" << endl; cout << *latepointer << endl;

*Pointer: dynamic variables/arrays Duh I am not expected to teach you these this week! new operator MyType *p; p = new MyType; dynamic variable delete operator

Pointer: use pointers with arrays The array name can be used as a pointer variable: Traversing array const int MAXSIZE = 5; double da[maxsize]; double* p;... for (double* p = da; p < da + MAXSIZE; p++) *p = 3.6; Passing arrays or portions to a function int findfirstnegative(const double a[], int n); // or its equivalent int findfirstnegative(const double* a, int n);... double b[5];... cout << findfirstnegative(b, 5); cout << findfirstnegative(b+2, 3);

Pointer: pointers with arrays example #include <iostream> #include <string> using namespace std; int main () { int i[][3] = { {1, 2, 3, {4, 5, 6; int* pointy = &i[1][1]; int* copypointy = pointy; *pointy = 100; pointy = &i[0][2]; cout << *pointy << endl; cout << *copypointy << endl;

Structure Structure is a collection of values of different types i.e. student record (int UID, string name) Variables inside a structure are member variables An instance of a structure is an object i.e. a student record for Bob is (104000000, Bob ) struct <structname> { <member1_type> <member1_name>; <member2_type> <member2_name>; //...etc. ; // Remember the semicolon!

Structure: declaration and the dot operator Use dot operator to specify a member variable of a structure variable struct Employee { string name; double salary; int age; ; // DON'T FORGET THE SEMICOLON!!! // Dot operator Employee e1; Employee e2; e1.name = "Fred"; e1.age = 60; e2.name = Ethel"; // Use struct array Employee company[100]; company[1].name = Ricky"; //...

Structure: use pointer and the arrow operator When using a pointer, you can use -> to specify a member variable (p->m means the same as (*p).m) struct Employee { string name; double salary; int age; ; // DON'T FORGET THE SEMICOLON!!! // use the array operator -> to set values // this is more convenient and preferred Employee *ep1; ep1 = new Employee; ep1->name = "Fred"; ep1->age = 60; // equivalently, you can use pointer // dereference and the dot operator // to set values Employee *ep2; ep2 = new Employee; (*ep2).name = "Ethel";

Structure: constructor A constructor is used to initialize the data members of a newly declared struct object #include <iostream> #include <string> using namespace std; struct Ford { // Data Member int tires; string model; // Constructor for Ford objects Ford () { tires = 5; // 4+1 Spare model = "Ranger"; ; int main () { // Constructor invoked below! Ford mycar; cout << mycar.tires << endl; cout << mycar.model << endl;

Structure: public & private tags Motivation: ensure the integrity of an object's data by restricting who can modify them The public tag in a struct, says "Everything that comes after this (until you say otherwise) is publicly accessible and modifiable." The private tag in a struct, says "Everything that comes after this (until you say otherwise) is ONLY accessible to member functions."

Structure: public & private tags example struct Ford { // Available to anyone! public: // Constructor Ford () { tires = 5; model = "Ranger"; // Can't touch these! private: int tires; string model; ; But how would you be able to access private members?

Structure: member function How to give users access to the private members? Member functions (methods), are functions that are called by instances of a particular struct. Member functions called getters are used to allow users access to viewing private member values. Member functions called setters are used to allow users to change private member values.

Structure: public & private tags example struct Ford { public: // Need function prototype int getflat(); void setflat(int t); // Constructor Ford () { tires = 5; private: int tires; ; // Member function definition int Ford::getFlat () { return tires; void Ford::setFlat (int t) { tires = t;

Class: a premier a class and a struct are the same thing in C++ [unlike C#] the only difference: instead of having all members default to public access, all members of classes default to private. class ClassExample { int x; double d; public: ClassExample () { x = 3; d = 3.333; ; void printx () { cout << x << endl;

Clarifications: strcpy v.s. strncpy char* strcpy (char* dst, const char* src); Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). char* strncpy (char* dst, const char* src, size_t num); Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it. No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

Clarifications: assignment = in array C-string values and C-string variables are not like values and variables of other data types, and many of the usual operations do not work for C-strings: You cannot use a C-string variable in an assignment statement using =. If you use == to test C-strings for equality, you will not get the result you expect. The reason for these problems is that C-strings and C-string variables are arrays. Assigning a value to a C-string variable is not as simple as it is for other kinds of variables. The following is illegal: char astring[10]; astring = "Hello"; Illegal! Although you can use the equal sign to assign a value to a C-string variable when the variable is declared, you cannot do it anywhere else in your program. Technically, the use of the equal sign in a declaration is an initialization, not an assignment. If you want to assign a value to a C-string variable, you must do something else, e.g. use predefined function strcpy as shown below: strcpy(astring, "Hello");