! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Similar documents
Functions, Arrays & Structs

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Functions, Arrays & Structs

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Week 4. Pointers and Addresses. Dereferencing and initializing. Pointers as Function Parameters. Pointers & Structs. Gaddis: Chapters 9, 11

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

Ch 11. Structured Data (11.2 to 11.8) Data Types Structures. Data Types (C/C++) Data Type: CS 2308 Fall example: Integer.

Homework #3 CS2255 Fall 2012

Data Types (C/C++) Structures

BITG 1113: POINTER LECTURE 12

Array Elements as Function Parameters

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

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

Ch 6. Functions. Example: function calls function

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

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

CS 115 Midterm 2 Solutions

CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

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

Structures. Data Types Structures. Data Types (C/C++) Gaddis: A Data Type consists of: Unit 7. example: Integer. CS 1428 Spring 2018

Pointers, Dynamic Data, and Reference Types

What is an algorithm?

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.

CS2255 HOMEWORK #1 Fall 2012

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

Lecture 23: Pointer Arithmetic

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

True or False (15 Points)

Ch. 17: Linked Lists. Introduction to Linked Lists

Overloading Operators

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

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

CSC1322 Object-Oriented Programming Concepts

Pointers. Variable Declaration. Chapter 10

Name Section: M/W or T/TH. True or False (14 Points)

Review of Important Topics in CS1600. Functions Arrays C-strings

True or False (12 Points)

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

Exam 3 Chapters 7 & 9

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

Pointers and Dynamic Memory Allocation

Week 3: File I/O and Formatting 3.7 Formatting Output

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

MYcsvtu Notes LECTURE 34. POINTERS

Name SECTION: 12:45 2:20. True or False (12 Points)

Pointers, Arrays and C-Strings

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

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

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

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

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

BITG 1113: Function (Part 2) LECTURE 5

Input And Output of C++

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

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Arrays. Arizona State University 1

CS 103 Unit 13 Slides

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a


7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values

True or False (14 Points)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Week 3: Pointers (Part 2)

Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

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

True or False (15 Points)

2. It is possible for a structure variable to be a member of another structure variable.

by Pearson Education, Inc. All Rights Reserved.

Pointers! Arizona State University 1

Object Reference and Memory Allocation. Questions:

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

Unit 14. Passing Arrays & C++ Strings

CSC 211 Intermediate Programming. Arrays & Pointers

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

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

CSCE Practice Midterm. Data Types

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

Pointer Data Type and Pointer Variables

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

7/21/10 MOTIVATION. Did you see Inception this weekend? COMP 10 EXPLORING COMPUTER SCIENCE. Lecture 6 Arrays

Reference operator (&)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Topics. Functions. Functions

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

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

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

Transcription:

Week 3 Pointers, References, Arrays & Structures Gaddis: Chapters 6, 7, 9, 11 CS 5301 Fall 2013 Jill Seaman 1 Arguments passed by value! Pass by value: when an argument is passed to a function, its value is copied into the parameter.! It is implemented using variable initialization (behind the scenes): int param = argument;! Changes to the parameter in the function body do not affect the value of the argument in the call! The parameter and the argument are stored in separate variables; separate locations in 2 memory. Example: Pass by Value Parameter passing by Reference! #include <iostream> using namespace std; void changeme(int); int number = 12; cout << "number is " << number << endl; changeme(number); cout << "Back in main, number is " << number << endl; return 0; int myvalue = number; void changeme(int myvalue) { myvalue = 200; cout << "myvalue is " << myvalue << endl; changeme failed to change the argument! number is 12 myvalue is 200 Back in main, number is 12 3! Pass by reference: when an argument is passed to a function, the function has direct access to the original argument (no copying).! Pass by reference in C++ is implemented using a reference parameter, which has an ampersand (&) in front of it: void changeme (int &myvalue);! A reference parameter acts as an alias to its argument, it is NOT a separate storage location.! Changes to the parameter in the function DO 4 affect the value of the argument

! Example: Pass by Reference #include <iostream> using namespace std; void changeme(int &); int number = 12; cout << "number is " << number << endl; changeme(number); cout << "Back in main, number is " << number << endl; return 0; myvalue is an alias for number, only one shared variable void changeme(int &myvalue) { myvalue = 200; cout << "myvalue is " << myvalue << endl; number is 12 myvalue is 200 Back in main, number is 200 5! An array is: Arrays - A series of elements of the same type - placed in contiguous memory locations - that can be individually referenced by adding an index to a unique identifier.! To declare an array: datatype identifier [size]; int numbers[5]; - datatype is the type of the elements - identifier is the name of the array - size is the number of elements (constant) 6 Array initialization! To specify contents of the array in the definition: float scores[3] = {86.5, 92.1, 77.5; - creates an array of size 3 containing the specified values. float scores[10] = {86.5, 92.1, 77.5; - creates an array containing the specified values followed by 7 zeros (partial initialization). float scores[] = {86.5, 92.1, 77.5; - creates an array of size 3 containing the specified values (size is determined from list). 7 Array access! to access the value of any of the elements of the array individually as if it was a normal variable: scores[2] = 89.5; - scores[2] is a variable of type float - use it anywhere a float variable can be used.! rules about subscripts: - always start at 0, last subscript is size-1 - must have type int but can be any expression! watchout: brackets used both to declare the array 8 and to access elements.

Arrays: operations! Valid operations over entire arrays: function call: myfunc(scores,x);! Invalid operations over structs: assignment: array1 = array2; comparison: array1 == array2 output: cout << array1; input: cin >> array2; Must do these element by element, probably using a for loop 9 Example: Processing arrays Computing the average of an array of scores: const int NUM_SCORES = 8; int scores[num_scores]; cout << Enter the << NUM_SCORES << programming assignment scores: << endl; for (int i=0; i < NUM_SCORES; i++) { cin >> scores[i]; int total = 0; //initialize accumulator for (int i=0; i < NUM_SCORES; i++) { total = total + scores[i]; double average = static_cast<double>(total) / NUM_SCORES; 10 Arrays as parameters! In the function definition, the parameter type is a variable name with an empty set of brackets: [ ] - Do NOT give a size for the array inside [ ] void showarray(int values[], int size)! In the prototype, empty brackets go after the element datatype. void showarray(int[], int)! In the function call, use the variable name for the array. showarray(numbers, 5)! An array is always passed by reference. 11 Example: Partially filled arrays int sumlist (int list[], int size) {//sums elements in list array int total = 0; for (int i=0; i < size; i++) { total = total + list[i]; return total; const int CAPACITY = 100; int scores[capacity]; int count = 0; //tracks number of elems in array cout << Enter the programming assignment scores: << endl; cout << Enter -1 when finished << endl; int score; cin >> score; while (score!= -1 && count < CAPACITY) { scores[count] = score; count++; cin >> score; int sum = sumlist(scores,count); sums from position 0 to size-1, even if the array is bigger. pass count, not CAPACITY 12

Multidimensional arrays Multidimensional arrays! multidimensional array: an array that is accessed by more than one index int table[2][5]; // 2 rows, 5 columns table[0][1] = 10; // puts 10 in first row, // second column! Initialization: int a[4][3] = {4,6,3,12,7,15,41,32,81,52,11,9; - First row: 4,6,3 - Second row: 12, 7, 15 - etc. 13! when using a 2D array as a parameter, you must specify the number of columns: void myfunction(int vals[ ][3], int rows) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < 3; ++j) cout << vals[i][j] << " "; cout << "\n"; int a[4][3] = {4,6,3,12,7,15,41,32,81,52,11,9;... myfunction(a,4);... 14 Structures Structures: operations! A structure stores a collection of objects of various types! Each element in the structure is a member, and is accessed using the dot member operator. struct Student { int idnumber; string name; int age; string major; ; Defines a new data type Student student1, student2; Defines new variables student1.name = John Smith ; 15 Student student3 = {123456, Ann Page,22, Math ;! Valid operations over entire structs: assignment: student1 = student2; function call: myfunc(gradstudent,x);! Invalid operations over structs: comparison: student1 == student2 output: cout << student1; input: cin >> student2; void myfunc(student, int); //prototype Must do these member by member 16

Arrays of Structures Pointers! You can store values of structure types in arrays. Student roster[40]; //holds 40 Student structs! Each student is accessible via the subscript notation. roster[0] = student1;! Members of structure accessible via dot notation cout << roster[0].name << endl; 17! Pointer: a variable that stores the address of another variable, providing indirect access to it.! The address operator (&) returns the address of a variable. int x; cout << &x << endl; // 0xbffffb0c! An asterisk is used to define a pointer variable int *ptr;! ptr is a pointer to an int. It can contain addresses of int variables. ptr = &x; 18 Pointers! The unary operator * is the dereferencing operator. Pointers as Function Parameters! Use pointers to implement pass by reference.! *ptr is an alias for the variable that ptr points to. int x = 10; int *ptr; //declaration, NOT dereferencing ptr = &x; //ptr gets the address of x *ptr = 7; //the thing ptr pts to gets 7! Initialization: int x = 10; int *ptr = &x; //declaration, NOT dereferencing! ptr is a pointer to an int, and it is initialized to the 19 address of x. //prototype: void changeval(int *); void changeval (int *val) { *val = *val * 11; int x; cout << "Enter an int " << endl; cin >> x; changeval(&x); cout << x << endl;! How is it different from using reference parameters? 20

Pointers and Arrays! You can treat an array variable as if it were a pointer to its first element. int numbers[] = {10, 20, 30, 40, 50; cout << first: << numbers[0] << endl; cout << first: << *numbers << endl; cout << &(numbers[0]) << endl; cout << numbers << endl; first: 10 first: 10 0xbffffb00 0xbffffb00 21 Pointer Arithmetic! When you add a value n to a pointer, you are actually adding n times the size of the data type being referenced by the pointer. int numbers[] = {10, 20, 30, 40, 50; // sizeof(int) is 4. // Let us assume numbers is stored at 0xbffffb00 // Then numbers+1 is really 0xbffffb00 + 1*4, or 0xbffffb04 // And numbers+2 is really 0xbffffb00 + 2*4, or 0xbffffb08 // And numbers+3 is really 0xbffffb00 + 3*4, or 0xbffffb0c cout << second: << numbers[1] << endl; cout << second: << *(numbers+1) << endl; cout << "size: " << sizeof(int) << endl; cout << numbers << endl; cout << numbers+1 << endl; second: 20 second: 20 size: 4 0xbffffb00 0xbffffb04! Note: array[index] is equivalent to *(array + index) 22 Pointers and Arrays! pointer operations can be used with array variables. int list[10]; cin >> *(list+3);! subscript operations can be used with pointers. int list[] = {1,2,3; int *ptr = list; cout << ptr[2]; Pointers to structures! We can define pointers to structures Student s1 = {12345, Jane Doe, 18, Math ; Student *ptr = &s1;! To access the members via the pointer: cout << *ptr.name << end; // ERROR: *(ptr.name)! dot operator has higher precedence, so use (): 23 cout << (*ptr).name << end;! or equivalently, use ->: cout << ptr->name << end; 24