1 Unit 14 Passing Arrays & C++ Strings
PASSING ARRAYS 2
3 Passing Arrays As Arguments Can we pass an array to another function? YES!! Syntax: Step 1: In the prototype/signature: Put empty square brackets after the parameter name if it is an array (e.g. int data[]) Step 2: When you call the function, just provide the name of the array // Function that takes an array int sum(int data[], int size); 1 int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; int vals[100]; /* some code to initialize vals */ 2 int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0;
4 Pass-by-Value & Pass-by-Reference What are the pros and cons of emailing a document by: Attaching it to the email Sending a link (URL) to the document on some cloud service (etc. Google Docs) Pass-by-value is like emailing an attachment A copy is made and sent Pass-by-reference means emailing a link to the original No copy is made and any modifications by the other party are seen by the originator
5 Arrays And Pass-by-Reference Single (scalar) variables are passed-by-value in C/C++ Copies are passed Arrays are passed-byreference Links are passed This means any change to the array by the function is visible upon return to the caller void dec(int); int y = 3; dec(y); cout << y << endl; return 0; void dec(int y) y--; Single variables (aka scalars) are passed-by-value but arrays are passed-by-reference void init(int x[], int size); int data[10]; init(data, 10); cout << data[9] << endl; // prints 0 return 0; void init(int x[], int size) // x is really a link to data for(int i=0; i < size; i++) x[i] = 0; // changing data[i]
6 But Why? If we used pass-by-value then we'd have to make a copy of a potentially HUGE amount of data (what if the array had a million elements) To avoid copying vast amounts of data, we pass a link // Function that takes an array int sum(int data[], int size); int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; 520 [0] vals 916 [99]?? main() data 520 [0] 916 [99]?? int vals[100]; /* some code to initialize vals */ int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0; sum() return val
7 So What Is Actually Passed? The "link" that is passed is just the starting address (e.g. 520) of the array in memory The called function can now use 520 to access the original array (read it or write new values to it) 520 [0] vals 916 [99]?? main() data 520 // Function that takes an array int sum(int data[], int size); int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; int vals[100]; /* some code to initialize vals */ int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0; sum() return val
8 Analogy The first house on the 3600 block of Catalina Ave. has the address 3600. How many houses are on that block? There is no way to know!! We would have to count that separately.
9 Arrays in C/C++ vs. Other Languages Notice that if sum() only has the start address it would not know how big the array is Unlike Java or other languages where you can call some function to give the size of an array, C/C++ require you to track the size yourself in a separate variable and pass it as a secondary argument 520 [0] vals 916 [99]?? main() 100 520 data 100 size // Function that takes an array int sum(int data[], int size); int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; int vals[100]; /* some code to initialize vals */ int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0; sum() return val
10 Summary Syntax: In the prototype/signature: Put empty square brackets after the parameter name if it is an array (e.g. void f1(int data[]) ) When you call the function, just provide the name of the array (e.g. f1(data); ) Functions only know what you pass them You must pass the size of the array as an additional parameter in addition to the link to the array Arrays are passed-by-reference meaning no copy is made and changes by a function are actually being made to the original The C++ std:: library provides some alternatives to "plain-old arrays", but you will learn about these in CS 103/104
STRINGS 11
12 Character Arrays Recall that in C/C++ string constants (the text in between " ") are just character arrays Each character consumes 1 element in the array Ends with the null character (e.g. 0 decimal or '\0' ASCII) This approach of using an array of char's to store a string is referred to as a C-String char str1[7] = "CS 102" /* Initializes the array to "CS 102"*/ str1[5] = '3'; // now "CS 103" cout << str1 << endl; // prints "CS 103" cin >> str1; // get a new string from // the user (suppose user // types "hello" cout << str1; Program Output: CS 103 hello Addr: Index: 520 [0] 521 [1] 522 [2] 523 [3] 524 [4] 525 [5] 526 [6] str1: 'C' 'S' ' ' '1' '0' '2' '\0' Computer Memory
13 C++ Strings In C++, the library adds a new object type named string and provides an easier alternative to working with plain-old character arrays Do's and Don'ts Do #include <string> Don't need to declare the size (i.e. [7]), just assign Do still use it like an array by using [index] to get individual characters Do still use cin/cout with strings Don't worry about how many characters the user types when inputting to a C++ string #include <iostream> #include <string> using namespace std; char str1[7] = "CS 102"; /* Initializes the array to "CS 102"*/ string str2 = "CS 102"; /* Initializes str2 to "CS 102"*/ str1[5] = '3'; // now str1 = "CS 103" str2[5] = '4'; // now str2 = "CS 104" cout << str1 << endl; // prints "CS 103" cout << str2 << endl; // prints "CS 104" cin >> str1; // If the user types more // than 6 chars..uh oh! cin >> str2; // str2 will adjust to // hold whatever the user // types
14 What Do Strings Do Strings simply abstract character arrays Behind the scenes strings are just creating and manipulating character arrays but giving you a simplified set of operators and functions Can concatenate (append) to a string with the + operator #include <iostream> #include <string> using namespace std; string str2 = "CS 102"; // str2 stores 6 chars. = "CS 102" str2 = "Computer Science"; // now str2 stores 16 characters // Can append using '+' or '+=' operator str2 = str2 + " is cool"; // now str2 stores 24 characters str2 616 24 CS 102 Plain-old character array Computer Science Plain-old character array Computer Science is cool Plain-old character array
15 String Size Strings track how big they are Call the.size() function on a string to get the number of characters stored in the string #include <iostream> #include <string> using namespace std; string str2 = "CS 102"; cout << str2.size() << endl; // 6 str2 = "Computer Science"; cout << str2.size() << endl; // 16 str2 = str2 + " is cool"; cout << str2.size() << endl; // 24
16 String Comparison C++ strings will perform lexicographic (alphabetical) comparison when comparison operators (<, >, ==, etc.) are applied Comparison operators do not work with plain old character arrays #include <iostream> #include <string> using namespace std; char str1[4] = "abc"; string str2 = "abc"; if( str1 == "abc" ) // doesn't work... if( str2 == "abc" ) // works..true... if( str1 < "aac" ) // doesn't work... if( str2 < "aac" ) // works..false... string str3 = "acb"; if( str3 > str2 )... // works..true
17 Substrings C++ strings allow you to produce a new string from a substring Call either of the 2 versions:.substr(start_index) or.substr(start_index, length) function on the string 1 st version generates substring from starting index location all the way to the end of the string 2 nd version generates substring from the starting index and includes the next 'length' characters Note: when a function has the same name but different options for parameters we say the function is overloaded Returns a new string Even if length is 1 (i.e. if length is 1 you might think you just get a char, but you still get a string) #include <iostream> #include <string> using namespace std; string str1 = "CS102"; string str2 = str1.substr(2); // str2 = "102" str1 = "Hello World"; str2 = str1.substr(6,5); // str2 = "World" str2 = str1.substr(0,1); // str2 = "H"