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

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

Arrays and Pointers in C. Alan L. Cox

primitive arrays v. vectors (1)

Linked List using a Sentinel

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.

C++ for Java Programmers

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

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

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

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

Pointers. Pointers. Pointers (cont) CS 217

Lecture on pointers, references, and arrays and vectors

Reference operator (&)

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

Language comparison. C has pointers. Java has references. C++ has pointers and references

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Mon, Jan 20, 2014

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

Pointers, Arrays and C-Strings

INTRODUCTION TO COMPUTER SCIENCE - LAB

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

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

CSC 270 Survey of Programming Languages. What is a Pointer?

Exercise 1.1 Hello world

Array Initialization

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

Pointers. Variable Declaration. Chapter 10

Fundamental of Programming (C)

Week 3: Pointers (Part 2)

Part 3: Function Pointers, Linked Lists and nd Arrays

C++/Java. C++: Hello World. Java : Hello World. Expression Statement. Compound Statement. Declaration Statement

Pointers, Dynamic Data, and Reference Types

C++ Programming Chapter 7 Pointers

Course organization. Course introduction ( Week 1)

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

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

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

Memory, Arrays & Pointers

Lab Instructor : Jean Lai

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

What is an algorithm?

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

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

Chapter 2. Procedural Programming

Programming, numerics and optimization

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

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

Arrays. Week 4. Assylbek Jumagaliyev

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Dynamic Allocation of Memory

Pointers and References

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

12. Pointers Address-of operator (&)

Programming Fundamentals and Methodology. COMP104: C++ Basics

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

Outline. 1 About the course

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Computer Programming. Pointers. Marius Minea. 20 November 2017

CA341 - Comparative Programming Languages

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Lecture 23: Pointer Arithmetic

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

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

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

Program template-smart-pointers-again.cc

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

C Pointers. 6th April 2017 Giulio Picierro

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

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

INFO-I308 Laboratory Session #2

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

CMSC 202 Midterm Exam 1 Fall 2015

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

BITG 1113: POINTER LECTURE 12

Program template-smart-pointers.cc

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

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Evolution of Programming Languages

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Understanding Pointers

pointers & references

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

Pointers. Pointer References

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

First of all, it is a variable, just like other variables you studied

CSC 211 Intermediate Programming. Arrays & Pointers

Contents of Lecture 3

Programming in C/C Lecture 2

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

Chapter 5 - Pointers and Strings

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Chapter 5 - Pointers and Strings

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

Transcription:

The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references

Memory regions 2 EACH C++ VARIABLE IS STORED IN A MEMORY REGION THE SIZE OF THE REGION DEPENDS ON THE VARIABLE S TYPE

Sizes of various types 3 cout << "sizeof(char) = " << sizeof(char) << endl; cout << "sizeof(char&) = " << sizeof(char&) << endl; cout << "sizeof(int) = " << sizeof(int) << endl; cout << "sizeof(int&) = " << sizeof(int&) << endl; cout << "sizeof(long int) = " << sizeof(long int) << endl; cout << "sizeof(bool) = " << sizeof(bool) << endl; cout << "sizeof(float) = " << sizeof(float) << endl; cout << "sizeof(double) = " << sizeof(double) << endl; cout << "sizeof(string) = " << sizeof(string) << endl;

Where in memory? Use address of op 4 32-bit architecture: an address is 4 bytes long 64-bit architecture: an address is 8 bytes long

Pointers 5 - A POINTER IS A VARIABLE THAT HOLDS A MEMORY ADDRESS - WE OFTEN WANT A POINTER TO A PARTICULAR TYPE - POINTERS ARE EXTREMELY POWERFUL (JAVA HIDES IT FROM US!)

Declaring pointers 6

Assigning and dereferencing int x = 10; int *i_ptr; i_ptr = &x; // i_ptr -> the 1st byte of the 4 bytes long x. cout << "x = " << x << endl; // this prints x = 10 cout << "x = " << *i_ptr << endl; // this also prints x = 10 7 *i_ptr = 20; cout << "x = " << x << endl; // this prints x = 20 cout << "x = " << *i_ptr << endl; // this also prints x = 20 int y = 30; i_ptr = &y; cout << "y = " << *i_ptr << endl; // this prints y = 30 *i_ptr = 40 cout << "y = " << y << endl; // this prints y = 40

Visualize 8 0x000000# int myint = 15 15 0xf3c453# int* ptr = &myint 0xf3c453# 0xffffff#

9

Pointers and references // pt.cpp: testing pointers #include <iostream> using namespace std; void swap(int *a, int *b) { int temp=*a; *a=*b; *b=temp; } int main() { int x = 1, y=9; swap(&x, &y); cout << "x = " << x << endl; // x = 9 cout << "y = " << y << endl; // y = 1 return 0; } 10 Note that the pointers a,b are passed by value

Pointers to objects and the -> operator 11 void print_reversed_sentence(const string* s_ptr) { int start; int end = s_ptr->length()-1; // or end = (*s_ptr).length() - 1 for (start = s_ptr->length()-1; start>=0; start--) { if ( ( (*s_ptr)[start] == ' ') && (start < end) ) { cout << s_ptr->substr(start+1,end-start) << ' '; end = start-1; } } } if (start < end) cout << s_ptr->substr(start+1,end-start+1) << endl; (*obj_ptr).member is the same as obj->member#

Pointer to pointer, ad infinitum #include <iostream> using namespace std; void swap(string **a, string **b) { string* temp = *a; *a = *b; *b = temp; } int main() { string 9irst("David"); string last("blaine"); string* p1 = &9irst; string* p2 = &last; } swap(&p1, &p2); cout << "p1 points to " << *p1 << endl; // "Blaine" cout << "p2 points to " << *p2 << endl; // "David" return 0; 12

Arrays 13 ARRAY SIZE MUST BE A CONSTANT EXPRESSION SOME EXTENSION ALLOWS DYNAMIC SIZE, NOT RECOMMENDED ARRAY NAME CAN BE USED AS A POINTER TO THE FIRST ELEMENT OF THE ARRAY

Definition and initialization 14 int main() { const size_t s = 5; int A[s]; int B[5] = {1, 2, 3, 4, 5}; int C[] = {1, 2, 3, 4, 5}; // the same as saying int C[5]... for (size_t i=0; i<s; i++) { A[i] = i*i; B[i] += A[i]; C[i] += B[i]; } for (size_t i=0; i<s; i++) cout << C[i] << ' '; cout << endl; return 0; }

Extension not recommended 15 int s = 5; int A[s]; // should not be allowed, but OK with g++ 4.x g++ -pedantic -ansi test_array.cpp... error: ISO C++ forbids variable-size array A!

C-style strings 16 char name[] = "David"; // name has 6 elements, the last is implicitly '\0' cout << sizeof(name) << endl; // prints 6 int i=0; while (name[i]!= '\0') cout << name[i++]; cout << endl; cout << name << endl; char name[5] = "David"; // compilation error

Initializing C-style string (char array) 17 #include <iostream> using namespace std; int main() { char name[] = "David"; char another[] = { 'D', 'a', 'v', 'i', 'd', '\0' }; cout << name << endl; cout << another << endl; return 0; }

String literals 18 The expression "David" is called a string literal char name[] = "This is a very long " "name and thus won't fit " "on a line"; cout << name; // get "This is a very long name and thus won't fit in a line"

Character arrays with \0 in the middle 19 Perfectly fine to have them; just be careful! char sa[] = "Only up to here\0the rest can still be printed"; cout << sa << endl; for (i=0; i< sizeof(sa); i++) { if (sa[i]!= '\0') cout << sa[i]; else cout << "[NULL CHAR]"; } cout << endl; string str_obj = sa; cout << str_obj; // prints "Only up to here"

Why do we care about C-style strings? They are very efficient Necessary in system programming Some C++ functions take C-style string arguments 20

Command line arguments 21 int main() int main(void) int main(int argc, char **argv) int main(int argc, char *argv[])

Multidimensional Arrays 22 const int m=2; const int n=3; int A[m][n] = { {1, 2, 3}, {4, 5, 6} }; // initialization must have bounds for all dimension, except the first int B[][n] = { {10, 20, 30}, {40, 50, 60} }; int C[m][n]; int i, j; for (i=0; i<m; i++) for (j=0; j<n; j++) C[i][j] = A[i][j] + B[i][j]; for (i=0; i<m; i++) { for (j=0; j<n; j++) { cout << setw(2) << C[i][j] << ' '; } cout << endl; }

Arrays and Pointers 23 - ARRAY NAME CAN BE USED AS POINTER - WE CAN NAVIGATE ARRAYS USING POINTER ARITHMETIC - POINTERS AND ARRAYS CAN BE USED INTERCHANGABLY IN ARGUMENT PASSING - - AN ARRAY NAME CAN BE THOUGHT OF AS A CONSTANT POINTER

Array name as constant pointer 24 int a[5] = {1,2,3,4,5}; int* i_ptr = &a[0]; // i_ptr points to a[0] i_ptr = a; // i_ptr points to a[0], equivalent to the above line *i_ptr = 10; // now a[0] == 10 int a[5]; int* i_ptr; i_ptr = a; // perfectly fine! a = i_ptr; // compilation error!

Traversing array using pointer arithmetic 25 int A[5] = {1, 2, 3, 4, 5}; int i; int* int_ptr; // we can traverse A like this for (i=0; i<5; i++) cout << A[i] << ' '; // or like this for (int_ptr=a; int_ptr!= A+5; int_ptr++) cout << *int_ptr << ' ';

Pointer arithmetic 26 int a = 123; int* int_ptr = &a; cout << "+0:" << int_ptr << endl; // +0:0x7fff6a9387c4 cout << "+1:" << int_ptr+1 << endl; // +1:0x7fff6a9387c8 cout << "+2:" << int_ptr+2 << endl; // +2:0x7fff6a9387cc

Pointer & array used interchangably in argument passing void ps1(char* s) { while (*s!= '\0') { cout << *s; s+ +; } } void ps2(char s[]) { while (*s!= '\0') { cout << *s; s+ +; } } 27 int main() { char* s1 = new char[7]; // create dynamically an array of 7 chars char s2[] = "abcde\n"; int i=0; while (s2[i]!= '\0') { s1[i] = s2[i]; i++; } ps1(s1); ps1(s2); // valid ps2(s1); ps2(s2); // also valid } delete [] s1;