1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures.

Slides:



Advertisements
Similar presentations
Strings.
Advertisements

Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
1 Classes with Pointer Data Members (II) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230.
The Art of Design Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo.
1 String Library and Stream I/O Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
1 Array, Pointer and Reference ( IV ) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures.
Array, Pointer and Reference ( V ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Midterm Review Ying Wu Electrical Engineering & Computer Science Northwestern University EECS230 Lectures Series.
1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Debugging: Catching Bugs ( II ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
1 Array, Pointer and Reference ( I ) Ying Wu Electrical Engineering and Computer Science Northwestern University EECS 230 Lectures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
1 Debugging: Catching Bugs ( II ) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures.
Array, Pointer and Reference ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
C++ Lecture 3 Monday, 14 July Arrays, Pointers, and Strings l Use of array in C++, multi- dimensional array, array argument passing l Pointers l.
1 C++ Classes (I) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Function ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
1 CSE 2341 Object Oriented Programming with C++ Note Set #2.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Lecture 15: Projects Using Similar Data. What is an Array? An array is a data structure consisting of related data items of the same type. Stored in a.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers Class #9 – Pointers Pointers Pointers are among C++ ’ s most powerful, yet most difficult concepts to master. We ’ ve seen how we can use references.
C++ Programming Lecture 17 Pointers – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Variables and memory addresses
1 Object-Oriented Programming Using C++ A tutorial for pointers.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 2/2/05CS250 Introduction to Computer Science II Pointers.
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Variables A piece of memory set aside to store data
CSC113: Computer Programming (Theory = 03, Lab = 01)
Reference Parameters.
CS150 Introduction to Computer Science 1
C++ Pointers and Strings
CS150 Introduction to Computer Science 1
Data Structures and Algorithms Introduction to Pointers
CS250 Introduction to Computer Science II
Pointers and dynamic objects
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Presentation transcript:

1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series

2 An unsolved question … What if I want to pass many parameters to a function, such as a set of numbers, or an array? What if I expect many outputs from a function, such as a set of numbers? Specifically, –How to compare two strings? –How to copy one string to another one? –How to change all the letters in a string to capital letters?

3 What will we learn today? A brief review of what we’ve learnt More on Call-by-Value and Call-by-Ref. Passing arrays to functions Array of pointers

4 A Brief Review Concepts: –Variable, type, value, pointer, reference When I declare an array, i.e., int a[3], what will happen in the memory? OS reserve a block of memory for a[3] compiler will not check the range of the array!!!  a[5] will not produce any syntax error a is a pointer, pointing to &(a[0]) int b = 2; int &c = b; // just an alias a[0] a[1] a[2] a b (c) &b &c

5 Calling Functions by Reference Call by reference –Pass address of argument –Allows you to change the original data in memory Pass a reference and pass a pointer void fun(int *); void main() { int n = 2; fun(&n); } void fun( int *ptr ) { (*ptr) *= 2; } void fun(int &); void main() { int n = 2; int &r_n = n; fun(r_n); // fun(n); // same } void fun( int &x ) { x *= 2; }

6 Question? Yes, I know how to pass a piece of data to a function. But if I have a set of data, (e.g., the grades of 100 students), –Q1: if my function is to calculate the average, how can I pass such a set of data to the function? –Q2: If my function is to adjust their grades, e.g., sqrt(x i )*10, how can I do that?

7 One Solution  A naïve solution –Call-by-value: you copy the whole array, and pass all of them through the function parameters int Avg(int a1, int a2, int a3, int a4, int a5, ……………… ); Why this solution is not sound? stack seg. a[0] a[1] a[2] a[99] Solution I s. p. a[1] data seg. a[0] a[99] a

8 A Better Solution! Solution: –Store all the data in an array –Then pass the address and the length of this array How does it work? Guess: what would be the function prototype look like? –How do I know where the array is located? –How do I know the size of the array? –How to tell my function what I pass is an array? a[1] data seg. a[0] a[99] a stack seg Solution II s. p.

9 Passing Arrays to Functions Function prototype: void modifyArray( int b[], int arraySize ); –Parameter names optional in prototype int b[] could be simply int [] int arraysize could be simply int void modifyArray( int [], int );

10 Example int Avg(int a[], int size); void Promote(int a[], int size); void main() { int score[10] = {80,90,70,75,95,100,85,90,70,95}; int mean; mean = Avg(score, 10); if(mean<80){ Promote(score, 10); } else{ cout << “Good!”; } #include int Avg(int a[], int size) { assert(size>0); int tmp = 0; for(int k=0;k<size;k++) tmp += a[k]; return tmp/size; } void Promote(int a[], int size) { for(int k=0; k<size; k++) a[k] = 10*sqrt(a[k]); }

11 A Trick! As we know, a rule of thumb is that –the name of an array is the address of the 1 st element, –or a pointer that points to the 1 st element So, we can roughly say –“an array and a pointer are equivalent”. Thus, we can use pointers for indexing –It is flexible and convenient. int a[10] = {1,2,3,4,5,6,7,8,9,10}; int *p = &(a[5]); p[0] = ? p[4] = ? p[5] =? –But, it is dangerous, as well.  C/C++ will never do the range check for you!

12 Passing pointers to functions int Avg(int *pa, int n); void Promote(int *pa, int n); void main() { int score[10] = {80,90,70,75,95,100,85,90,70,95}; int mean; mean = Avg(score, 10); if(mean<80){ Promote(score, 10); } else{ cout << “Good!”; } #include int Avg(int *pa, int n) { assert(n>0); int tmp = 0; for(int k=0;k<n;k++) tmp += pa[k]; return tmp/size; } void Promote(int *pa, int n) { for(int k=0; k<n; k++) pa[k] = 10*sqrt(pa[k]); }

13 To ensure yourself! The basic idea of CBR is to let you pass an address to functions, such that –You can pass a set of data to functions –You let the function modify the original data To use CBR, your function will –Either make modification of the originals –Or doesn’t You, as a programmer, must be sure of that. –If you don’t allow the function change the original data, then a good practice is to use a specific modifier “ const ” to indicate –If your function does modify the data which is not what you want, then the Compiler will let you know, and reduce the risk.

14 Using const int Avg(const int *pa, int n); void Promote(int *pa, int n); void main() { int score[10] = {80,90,70,75,95,100,85,90,70,95}; int mean; mean = Avg(score, 10); if(mean<80){ Promote(score, 10); } else{ cout << “Good!”; } #include int Avg(const int *pa, int n) { assert(n>0); int tmp = 0; for(int k=0;k<n;k++) tmp += pa[k]; return tmp/size; } void Promote(int *pa, int n) { for(int k=0; k<n; k++) pa[k] = 10*sqrt(pa[k]); }

15 Wanna Compare two strings? bool CmpStr(const char *str1, const char *str2) { boolres = true; int index = 0; do{ if(str1[index] != str2[index]){ res = false; break; } index ++; } while(str1[index] != 0) return res; }

16 strcmp() C/C++ string library ( prototypes defined in string.h) int strcmp(const char *str1, const char *str2); Return value >0 if str1>str2 =0if str1==str2 <0 if str1<str2 E.g. “abc” < “bbc” “abc” < “acd” “abc” < “abd”

17 Wanna Copy a string? void CpyStr(char *to, const char *from) { int index = 0; while(from[index]!=0){ to[index] = from[index]; index ++; } to[index] = ‘\0’; }

18 Alert! When copying a string, you need to “reserve” enough space to hold the new string! //Will it work? void main() { char str1[] = “How are you!”; char *str2; CpyStr(str2, str1); CpyStr(str2, “fine”); } // will it work? void main() { char str1[] = “How are you!”; char str2[6]; CpyStr(str2, str1); CpyStr(str2, “fine”); }

19 Strcpy() C/C++ string library defines strcpy() char *strcpy( char *to, const char *from ); Return: the destination string. No return value is reserved to indicate an error. void main() { char string[80]; if ( strcpy( string, "Hello world!" )) cout << string << endl; else cout << “copying failed! << endl; }

20 Arrays of Pointers Arrays can contain pointers –Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" }; –Each element of suit is a pointer to a char * (a string) –The strings are not in the array, only pointers to the strings are in the array –suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’