280 likes | 397 Views
ECE 264 Object-Oriented Software Development. Instructor: Dr. Honggang Wang Spring 2013 Lecture 14: strings and pointer. Lecture outline. Announcements / reminders Project groups: e-mail Dr. Wang by Thur., March 28 Each group consists of 4-5 students
E N D
ECE 264Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 14: strings and pointer
Lecture outline • Announcements / reminders • Project groups: e-mail Dr. Wang by Thur., March 28 • Each group consists of 4-5 students • Those who don’t choose a group will be randomly assigned • Can e-mail me with “sub-group”; I’ll fill rest of group • Lab 7 will posted today • Today • Review: Arrays & vectors • Other container classes • Strings • Pointer ECE 264: Lecture 14
Review: Arrays • Constant size list of items of same type • Can initialize using comma-separated list: • int n[] = {10, 20, 30, 40, 50}; • Can access individual elements using [] • cout << n[1]; would print 20 • Can pass arrays to functions • void printArray(int arr[], int size); • Pitfalls • Indexing past array boundaries • Array name is a pointer passed by reference ECE 264: Lecture 14
Review: Vectors • Vectors allow programmer to create “arrays” that: • Are dynamically resizable • Can be assigned to one another • Can be compared for equality • Contain easier generic boundary checking • Can access vectors like arrays: v[0] • Can also use vector functions • Examples: vector <double> list; //empty vector vector<string> wordList(n); //capacity:n strings //vector of 8 integers, each initialized to 0 vector<int> intList(8,0); ECE 264: Lecture 14
Review: Vector methods • Common member functions: • bool empty(): true if vector contains no values • void pop_back(): deletes last element in vector • Does not actually return the element • Gives an error if vector is empty • void push_back(element): add element to end of vector • void resize(int): changes the size of vector • size_t size(): returns the size of vector • <el> at(<el>): allows you to insert element in vector, but also provides boundary checking • <el>: type of elements stored in the vector (e.g. int, double) • void clear(): removes all elements from vector ECE 264: Lecture 14
Additional container classes • C++ standard template library contains other useful containers • list: doubly-linked list • Allows for efficient element insertion • Can also push/pop front of list; sort, merge, reverse lists • queue: FIFO queue • Has simple push/pop operations • priority_queue: sorted queue with largest element first • stack: LIFO stack • Can access top of stack ECE 264: Lecture 20
Standard Library Class string • Class string • Header <string>, namespace std • We’ve seen: • Initialization: string s1( "hi" ); • Input/output (as in cout << s1) • Assignment: s1 = "hi"; • Can also use: • Relational operators: ==, !=, >=, >, <=, < • Perform char-by-char comparison using ASCII values • Concatenation: += • E.g.: s1 += “lly” s1 = “hilly” ECE 264: Lecture 14
Standard Library Class string (Cont.) • Class string (Cont.) • Substring member function substr • s1.substr( 0, 14 ); • Starts at location 0, gets 14 characters • s1.substr( 15 ); • Substring beginning at location 15, to the end • Overloaded [] • Access one character • No range checking (if subscript invalid) • Member function at • Accesses one character • Example • s1.at( 10 ); • Has bounds checking, throws an exception if subscript is invalid ECE 264: Lecture 20
Example: Strings & functions int main() { string s1( "happy" ); string s2( " birthday" ); string s3; // test overloaded equality and relational operators cout << "s1 is \"" << s1 << "\"; s2 is \"" << s2 << "\"; s3 is \"" << s3 << '\"' << "\n\nThe results of comparing s2 and s1:" << "\ns2 == s1 yields " << ( s2 == s1 ? "true" : "false" ) << "\ns2 != s1 yields " << ( s2 != s1 ? "true" : "false" ) << "\ns2 > s1 yields " << ( s2 > s1 ? "true" : "false" ) << "\ns2 < s1 yields " << ( s2 < s1 ? "true" : "false" ) << "\ns2 >= s1 yields " << ( s2 >= s1 ? "true" : "false" ) << "\ns2 <= s1 yields " << ( s2 <= s1 ? "true" : "false" ); ECE 264: Lecture 14
Example (cont.) Output from previous slide: s1 is “happy”; s2 is “ birthday”; s3 is “” The results of comparing s1 and s2: s2 == s1 yields false s2 != s1 yields true s2 > s1 yields false s2 < s1 yields true s2 >= s1 yields false s2 <= s1 yields true ECE 264: Lecture 14
Example (cont.) // test string member function empty cout << "\n\nTesting s3.empty():" << endl; if ( s3.empty() ) { cout << "s3 is empty; assigning s1 to s3;" << endl; s3 = s1; // assign s1 to s3 cout << "s3 is \"" << s3 << "\""; }// end if // test overloaded string concatenation operator cout << "\n\ns1 += s2 yields s1 = "; s1 += s2; // test overloaded concatenation cout << s1; // test concatenation operator with C-style string cout << "\n\ns1 += \" to you\" yields" << endl; s1 += " to you"; cout << "s1 = " << s1 << "\n\n"; ECE 264: Lecture 14
Example (cont.) Output from previous slide: Testing s3.empty(): s3 is empty; assigning s1 to s3; s3 is “happy” s1 += s2 yields s1 = happy birthday s1 += “ to you” yields s1 = happy birthday to you ECE 264: Lecture 14
Example (cont.) // test string member function substr cout << "The substring of s1 starting at location 0 for\n" << "14 characters, s1.substr(0, 14), is:\n" << s1.substr( 0, 14 ) << "\n\n"; // test substr "to-end-of-string" option cout << "The substring of s1 starting at\n" << "location 15, s1.substr(15), is:\n" << s1.substr( 15 ) << endl; // test using subscript operator to create lvalue s1[ 0 ] = 'H'; s1[ 6 ] = 'B'; cout << "\ns1 after s1[0] = 'H' and s1[6] = 'B' is: " << s1 << "\n\n"; // test subscript out of range with string member function "at" cout << "Attempt to assign 'd' to s1.at( 30 ) yields:" << endl; s1.at( 30 ) = 'd';// ERROR: subscript out of range return 0; } // end main ECE 264: Lecture 14
Example (cont.) Output from previous slide: The substring of s1 starting at location 0 for 14 characters, s1.substr(0, 14), is: happy birthday The substring of s1 starting at location 15, s1.substr(15), is: to you s1 after s1[0] = ‘H’ and s1[6] = ‘B’ is: Happy Birthday to you Attempt to assign ‘d’ to s1.at(30) yields abnormal program completion ECE 264: Lecture 20
Dynamic memory allocation • Up until now, allocated memory statically • Assumed we knew data size at compile time • What if data size is input-dependent and unknown until run time? • In C, dynamic memory allocation handled through mallocand free • In C++, we use newanddelete ECE 264: Lecture 14
Refresher on pointers • Allocators (malloc, new) return pointer to allocated space • Pointer: address of another object • We implicitly use these when we pass function arguments by reference in C++ • Can get address of existing object using & • Can get value of existing pointer using * • Pointer declaration: <base type>* <pointer name> • Base type determines how reference is interpreted • Be careful when declaring multiple pointers • Be sure to initialize pointer before use ECE 264: Lecture 14
Pointer example int *iPtr, i=6; char* s, str[] = "example"; double *dPtr, d=1.25; iPtr s dPtr i str d 6 "example" 1.25 ECE 264: Lecture 14
x xp ip Pointer assignment • The assignment operator (=) is defined for pointers of the same base type. • The right operand of the assignment operator can be any expression that evaluates to the same type as the left operand. • Example: int x, *xp, *ip; xp = &x; ip = xp; ECE 264: Lecture 14
Arrays and pointers • Array name is a pointer to first array element • Can use pointers and arrays interchangeably • You can use [] to “index” a pointer • Example: char myString[] = "This is a string"; char *str; str = myString; for(int i =0; str[i]; i++) //look for null cout << str[i]; • What does this print? ECE 264: Lecture 14
Initialize the Pointer • Both define the pointer student and initialize student to the address of the first element in section: int section[80]; int *student = section; • Is equivalent to int section[80]; int *student = §ion[0]; • The pointer string is initialized to point to the character a in the string "abcd". char *string = "abcd"; ECE 264: Lecture 14
Pointer arithmetic • When using pointers/arrays interchangeably, can make use of pointer arithmetic • Can’t change where array name points, but you can change pointer • If p is a pointer, p++ means “point to next element” • “Next element” determined by base type • Can compare pointers • p == NULL pointer points nowhere • p == q p and q point to same location • Example int num[4] = {1,2,3,4}, *p; p = num; //same as p = &num[0]; cout << *p <<endl; ++p; cout << *p; ECE 264: Lecture 14
Practice! int q=6; int *iPtr = &q; cout << "iPtr is " << iPtr << endl; cout << "*iPtr is " << *iPtr << endl; cout << "++*iPtr, is " << ++*iPtr << endl; cout << "q is " << q << endl; cout << "iPtr is " << iPtr << endl; cout << "*iPtr++ is " << *iPtr++ << endl; cout << "iPtr is " << iPtr << endl; cout << "q is " << q << endl; Complete the output: iPtr is 0x7fff2f14 ECE 264: Lecture 14
Result of Practice iPtr is 0x7fff2f14 *iPtr is 6 ++*iPtr is 7 q is 7 iPtr is 0x7fff2f14 *iPtr++ is 7 iPtr is 0x7fff2f18 q is 7 ECE 264: Lecture 14
0xfff4c252 myString T h i s i s a s t r i n g \0 strPtr 0xfff4c252 Practice #2 char myString[ ] = "This is a string"; char *strPtr; strPtr = myString; cout << *myString << endl; cout<<myString << endl; cout << *(myString + 1) << endl; strPtr++; cout << *++strPtr << endl; myString++; //not legal • What does this print? ECE 264: Lecture 14
Practice #2 result • T • This is a string • h • i ECE 264: Lecture 14
Common Pointer Problems • Using uninitialized pointers int *iPtr; *iPtr = 100; • iPtr has not been initialized. The value 100 will be assigned to some memory location. Which one determines the error. • Incorrect/unintended syntax. ECE 264: Lecture 14
Example #include <iostream> int main() { char *aString = "What happens here?"; int len=0; while(*aString++ != '\0') len++; std::cout << len << ": " << aString; return 0; } • Does this compile? If not, why? • If it does, what is the output? Explain ECE 264: Lecture 14
Final notes • Next time • Start dynamic allocation • Midterm Survey • Acknowledgements: this lecture borrows heavily from lecture slides provided with the following texts: • Deitel & Deitel, C++ How to Program, 8th ed. • Etter & Ingber, Engineering Problem Solving with C++, 2nd ed. ECE 264: Lecture 14