C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Similar documents
Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

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

Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

Lecture 2: C Programm

REFERENCES, POINTERS AND STRUCTS

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

C'Programming' data'separate'from'methods/functions' Low'memory'overhead'compared'to'Java'

CS61C : Machine Structures

Homework #3 CS2255 Fall 2012

[0569] p 0318 garbage

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

CS61C : Machine Structures

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

CS61C : Machine Structures

CS 61c: Great Ideas in Computer Architecture

More C Pointer Dangers

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Introduction to Computer Science Midterm 3 Fall, Points

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

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

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

CSC 211 Intermediate Programming. Arrays & Pointers

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

HW1 due Monday by 9:30am Assignment online, submission details to come

Pointers and Arrays 1

C++ for Java Programmers

Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = "abc";! How do you tell how long a string is?!

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

ECE 15B COMPUTER ORGANIZATION

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CS201- Introduction to Programming Current Quizzes

CS61C : Machine Structures

What is an algorithm?

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Pointers, Arrays and C-Strings

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

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

Memory, Arrays, and Parameters

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

Pointers and File Handling

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

C Pointers. 6th April 2017 Giulio Picierro

Introduction to Scientific Computing and Problem Solving

CS61C : Machine Structures

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Week 5 9 April 2018 NWEN 241 More on pointers. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

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

Exam 3 Chapters 7 & 9

Arrays and Pointers in C. Alan L. Cox

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Today s lecture. Continue exploring C-strings. Pointer mechanics. C arrays. Under the hood: sequence of chars w/ terminating null

Object oriented programming C++


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

Name :. Roll No. :... Invigilator s Signature :.. CS/B.TECH (NEW)/SEM-2/CS-201/ BASIC COMPUTATION & PRINCIPLES OF COMPUTER PROGRAMMING

Solution Manual for Data Structures and Problem Solving Using C++ 2nd edition by Mark A. Weiss

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays and Pointers (part 1)

Assist. Prof. Dr. Caner ÖZCAN

Understanding Pointers

CSE 333 Midterm Exam 5/10/13

MORE STRINGS AND RECURSION

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

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

POINTERS. Pointer is a memory variable which can store address of an object of specified data type. For example:

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Reference operator (&)

CS31 Discussion 1E Spring 17 : week 08

EM108 Software Development for Engineers

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

Midterm Sample Questions. a) What evaluates to FALSE in C? What evaluates to TRUE?

Module 6: Array in C

DECLARAING AND INITIALIZING POINTERS

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

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

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Pointers, Arrays and Parameters

Pointers. Memory. void foo() { }//return

FORM 2 (Please put your name and form # on the scantron!!!!)

CS2255 HOMEWORK #1 Fall 2012

Arrays and Pointers (part 1)

Goals of this Lecture

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

BASIC ELEMENTS OF A COMPUTER PROGRAM

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Week 8. Muhao Chen

Ch. 11: References & the Copy-Constructor. - continued -

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Multidimension array, array of strings

School of Science and Technology

Transcription:

C++ ARRAYS POINTERS POINTER ARITHMETIC Problem Solving with Computers-I

General model of memory Sequence of adjacent cells Each cell has 1-byte stored in it Each cell has an address (memory location) Memory address 0 1 2 3 4 5 6 7 8 9 10 Value stored

C++ Arrays List of elements All elements have the same data type The elements re located adjacent to each other in memory Declare an array to store 3 integers

Accessing elements of an array scores 0 1 2 int scores[]={20,10,50}; // declare and initialize //Print each element // Use a for loop

C++11 range based for loops scores 0 1 2 int scores[]={20,10,50}; // declare an initialize //Print each element using a range based for loop (C++ 11 feature)

Modifying the array scores 0 1 2 int scores[]={20,10,50}; // declare an initialize //Increment each element by 10

Tracing code involving arrays arr 0 1 2 int arr[]={10,20,30}; int tmp = arr[0]; arr[0] = arr[2]; arr[2] = tmp; Choose the resulting array after the code is executed A. B. C. 10 20 30 arr 0 1 2 20 10 30 arr 0 1 2 30 20 10 arr 0 1 2 D. None of the above

Most common array pitfall- out of bound access scores[0] scores[1] scores[2] int scores[]={20,10,50}; // declare an initialize for(int i=0; i<=3; i++) scores[i] = scores[i]+10; Demo: Passing arrays to functions

Passing arrays to functions scores 10 20 30 40 50 0x2000 int main(){ int scores[]={10, 20, 30, 40, 50}; foo(scores); } double foo(int sc[]){ cout<<sc; return } What is the output? A. 10 B. 10 20 30 40 50 C. 0x2000 D. None of the above

Pointers 10 Pointer: A variable that contains the address of another variable Declaration: type * pointer_name; int* p;

How to make a pointer point to something 11 int *p; 100 112 int y = 3; p y To access the location of a variable, use the address operator &

Pointer Diagrams: Diagrams that show the relationship between pointers and pointees p points to y 100 112 Pointer: p p 112 y 3 Pointee: y 12

13 You can change the value of a variable using a pointer! int *p, y; y = 3; p = &y; *p = 5;

14 Two ways of changing the value of a variable Change the value of y directly: p y 3 Change the value of y indirectly (via pointer p):

15 Tracing code involving pointers int *p; int x=10; p = &x; *p = *p + 1; Q: Which of the following pointer diagrams best represents the outcome of the above code? A. x 10 B. x 11 p p C. Neither, the code is incorrect

Pointer assignment 16 int *p1, *p2, x; p1 = &x; p2 = p1; Q: Which of the following pointer diagrams best represents the outcome of the above code? A. x B. x p1 p1 p2 p2 C. Neither, the code is incorrect

Arrays and pointers 100 104 108 112 116 ar 20 30 50 80 90 ar is like a pointer to the first element ar[0] is the same as *ar ar[2] is the same as *(ar+2) Use pointers to pass arrays in functions Use pointer arithmetic to access arrays more conveniently

Pointer Arithmetic int ar[]={20, 30, 50, 80, 90}; How many of the following are invalid? I. pointer + integer (ptr+1) II. integer + pointer (1+ptr) III. pointer + pointer (ptr + ptr) IV. pointer integer (ptr 1) V. integer pointer (1 ptr) VI. pointer pointer (ptr ptr) VII. compare pointer to pointer (ptr == ptr) VIII. compare pointer to integer (1 == ptr) IX. compare pointer to 0 (ptr == 0) X. compare pointer to NULL (ptr == NULL) #invalid A: 1 B: 2 C: 3 D: 4 E: 5

Pointer Arithmetic int ar[]={20, 30, 50, 80, 90}; int *p; p = arr; p = p + 1; *p = *p + 1; Draw the array ar after the above code is executed

char arrays, C-strings How are ordinary arrays of characters and C-strings similar and how are they dissimilar?

What is the output of the code? char s1[] = "Mark"; char s2[] = "Jill"; for (int i = 0; i <= 4; i++) s2[i] = s1[i]; if (s1 == s2) s1 = "Art"; cout<<s1<<" "<<s2<<endl; A. Mark Jill B. Mark Mark C. Art Mark D. Compiler error E. Run-time error

22 Two important facts about Pointers 1) A pointer can only point to one type (basic or derived ) such as int, char, a struct, another pointer, etc 2) After declaring a pointer: int *ptr; ptr doesn t actually point to anything yet. We can either: make it point to something that already exists, OR allocate room in memory for something new that it will point to

Pointer Arithmetic What if we have an array of large structs (objects)? C++ takes care of it: In reality, ptr+1 doesn t add 1 to the memory address, but rather adds the size of the array element. C++ knows the size of the thing a pointer points to every addition or subtraction moves that many bytes: 1 byte for a char, 4 bytes for an int, etc.

Next time References Call by value, call by reference and call by address