Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1400 Chapters 9, 10 C-strings and Pointers. A few C-string library functions… #include int strcmp (char a[ ], char b[ ]); returns 0 if string a is.

Similar presentations


Presentation on theme: "CS 1400 Chapters 9, 10 C-strings and Pointers. A few C-string library functions… #include int strcmp (char a[ ], char b[ ]); returns 0 if string a is."— Presentation transcript:

1 CS 1400 Chapters 9, 10 C-strings and Pointers

2 A few C-string library functions… #include int strcmp (char a[ ], char b[ ]); returns 0 if string a is greater than string b int strlen (char a[ ]); returns the number of characters in string a void strcpy (char dest[ ], char source[ ]); copies the source string into the destination array (including the null), but does no bounds checking.

3 More C-string functions… void strncpy (char d[ ], char s[ ], int length); copy exactly length characters from string s into string d. void strcat (char d[ ], char s[ ]); copy string s onto the end of string d char* strstr (char s[ ], char p[ ]); return a pointer to the first occurrence of string p in string s – or NULL if not found.

4 Arrays of C-strings Arrays of C-strings are just 2-D arrays of characters char names[10][30]; // 10 names of up to 29 chars ea. Rules of thumb: names refers to the entire array of names and is used to pass the array to a function. names[n] refers to a single name and can be used to pass a single name to a function or for input and ouput. names[n][m] refers to a single character – all char operations are available.

5 Examples cin >> names[2]; –inputs a name into row 2 (the 3 rd name) names[2][1] = ‘x’; –changes the 2 nd character in row 2 to ‘x’ MyFunc (names); –passes the entire list of names to a function with this prototype; void MyFunc (char thesenames[ ] [30]); MyFunc2 (names[2]); –passes the 3 rd name to a function with this prototype; void MyFunc2 (char thisname[ ]);

6 Example… Consider a file of 100 student names and grades called “students.txt” Write a program to accept a name from the user and then output this student’s grade. Fred93.4 John87.1 Cheryl96.9 Shannon81.2 George77.2 ……

7 Pseudocode… read in database from a file into two parallel arrays get a particular name from the user do a linear search for the name output the corresponding grade

8 int main ( ) { char names[100][30], thisname[30]; float grades[100]; ifstream fin; fin.open (“students.txt”); for (int n=0; n<100; n++) fin>>names[n] >> grades[n]; cout << “enter a name: “; cin >> thisname; cout << “the grade is: “ << grades[ LinearSearch(names, 100, thisname) ] << endl; return 0; }

9 LinearSearch() for C-strings… int LinearSearch (char list[ ][30], int size, char value[ ]) { bool found = false; int position = -1; for (int n=0; n<size && !found; n++) { if (strcmp(list[n], value) == 0) { position = n; found = true; } return position; }

10 SelectionSort() for C-strings void SelectionSort (char array[ ][30], int size) { int smallest_position; for (int n=0; n<size-1; n++) smallest_position = FindSmallest (array, n, size); Swap (array, n, smallest_position); }

11 Swap() for C-strings void Swap (char a[ ][30], int n, int k) { char temp[30]; strcpy (temp, a[n]); strcpy (a[n], a[k]); strcpy (a[k], temp); }

12 FindSmallest() for C-strings int FindSmallest (char array[ ][30], int start, int size) { int position; char smallest[30]; strcpy (smallest, array[start]); // first assumption for (int k=start+1; k<size; k++) if (strcmp (array[k], smallest) < 0) { strcpy (smallest, array[k]); // change your mind position = k; // and remember pos. } return position; }

13 Common interview question… Write a program that prints out the numbers 1 to 100 on their own line; except if the number is a multiple of 3, write only the word “Fizz” on its own line, if the word is a multiple of 5, write only the word “Buzz” on its own line, and if the word is a multiple of both, write only the word “FizzBuzz” on its own line.

14 Example output lines… 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz …

15 int main() { for (int n=1; n<=100; n++) {if ((n%3 == 0) && (n%5 == 0)) cout << “FizzBuzz\n”; else if (n%3 == 0) cout << “Fizz\n”; else if (n%5 == 0) cout << “Buzz\n”; else cout << n << endl; } (Addresses are typically given in hexadecimal notation)

16 Example… Write a program that will accept a textual file name and then output all the words in that file that are miss-spelled A spell-checker! Enter filename: myletter.txt Miss-spelled words: ardvarc reciept requiam

17 Quiz Write a function named TitleMe() that accepts an argument containing a name as its first parameter and returns a new name result as its second parameter. If the first argument contains the name “Emily”, the function should prepend the title “Miss” to the create the new name. Otherwise, the function should prepend the title “Mr”. The function should then return the modified new name to the caller. Example use: char name[30], newname[30]; cin >> name; TitleMe (name, newname); cout << newname << endl;

18 Pointer variables A variable may be declared to hold an address using the * symbol float *fptr;// may hold an address of a float short *iptr;// may hold an address of a short The address of a variable or cell may be determined using the & operator float b = 3.14; short c = 567; fptr = &b; iptr = &c;

19 fptr iptr 3.1400000 0x400 0x500 567 or more commonly diagrammed using arrows… fptr iptr 3.1400000 0x400 0x500 567 a b a b

20 Using pointer variables A cell value pointed to by a pointer variable may be dereferenced using the * operator cout << *iptr; // output value pointed to by iptr cout << *fptr; // output value pointed to by fptr So, the * operator means “value pointed to by”

21 Pointers vs. References A reference and a pointer both refer or point to a memory location. –A reference is managed by the system –A pointer is managed by the programmer

22 Confusing use of * Be careful! –When used in a declaration, * creates a pointer variable int *ptr; –When used as a unary operator, * resolves or dereferences (uses) a pointer. cout << *ptr; –When used between two values, * means multiply cout << cost * rate;

23 Confusing use of & Be careful! –When used in a declaration, & creates a reference variable void MyFunc (int &ptr); –When used as a unary operator, & determines a pointer. cout << &ptr;

24 Special pointer constant… NULL refers to an invalid pointer. (The numeric value of NULL is usually 0). –Example: float *xptr = NULL;

25 Pointers may be passed as function parameters… void MyFunc (int *p1, int *p2); int main() { int x = 55, y = 77; MyFunc (&x, &y); cout << x << “, “, << y << endl; }

26 void MyFunc (int *p1, int *p2) { int temp; temp = *p1; *p1 = *p2; *p2 = temp; } So… what does this function do?

27 Arrays and pointers When an array is declared, the system creates the array cells and a pointer variable to the array: char letters[5] = “HELP”; letters 0x100 0x101 0x102 0x103 0x104 help\0 (Addresses are typically given in hexadecimal notation)

28 Different data types my require different sized cells short x[3] = {100, 200, 300}; // each cell is two bytes float y[2] = {1.2, 3.4}; // each cell is four bytes xyxy 0x200 0x202 0x204 0x300 0x304 100 200 300 1.20000000 3.40000000

29 sizeof() function The number of bytes utilized by a particular system for a variable may be determined by the sizeof() function; The argument to sizeof() may be a type or a variable name cout << sizeof(short) << sizeof(float); cout << sizeof(x) << sizeof(y);

30 Pointer arithmetic Pointer variables may be incremented, decremented, or have constants added or subtracted. When a pointer variable is incremented, the computer will automatically increment the address by the appropriate number of cells – regardless of their size

31 Examples… float x[4] = {1.2, 3.4, 5.6, 7.8}; float *fptr = &x[0]; cout << *fptr << endl; fptr++; cout << *fptr << endl; fptr += 2; cout << *fptr << endl;

32 The * and & operators have high precedence… int cost, *value, temp, rate; value = &rate; cin >> cost >> rate; temp = cost * * value; What would be stored in temp if the user enters 2.5 and 2?

33 Examples… char letters[5] = “HELP”; cout << *letters << endl; cout << letters[0] << endl; cout << *(letters+2) << endl; cout << letters[2] << endl; letters++; // illegal – letters is a constant // pointer (a reference managed // by the system)!

34 Passing arrays… What is being passed? MyFunc (letters); What should the function prototype be? void MyFunc (char array[ ]);// ?? void MyFunc (char *array);// ?? Either! These are equivalent: The parameter array is a pointer to a char array.

35 Equivalent notation… Pointer notation Array notation void MyFunc (char *array); void MyFunc (char array[ ]); *(array+1) = ‘x’; array[1] = ‘x’; MyFunc (letters); MyFunc (&letters[0]); float *fptr; float fptr[ ]; MyFunc (letters+n); MyFunc (&letters[n]);

36 Pointer-notation examples; Output the contents of an array Implement strlen() Sum an array Implement toupper() Implement islower()

37 So what? We have learned an alternate method to manipulating arrays Most array operations can be written using brackets or pointers One array operation can only be done using pointers

38 Dynamically allocated memory Using pointers, array space can be allocated manually to a size determined at run-time! int size; float *listptr; cout << “Enter list size: “; cin >> size; listptr = new float[size] ; Once an array has been dynamically allocated, the rest of the program can use pointers or brackets – your choice!

39 Example Write a program to read a file of float numbers and output them in numeric (sorted) order. –The first line of the file contains the number of values. For example… 2000 3.14 4.56 …

40 Deallocating… Memory allocated using new can be manually deallocated using delete delete [ ] docptr; Memory allocated using new that is not manually deallocated is automatically deallocated when a program exits

41 2-D arrays and pointers You may visualize a 2-D array as follows; char names[5][10]; namesnames[n]names[n][m]

42 Sorting arrays with pointers Consider a table of long names; John Jacob Jinglehiemer Schmidt Alloitious Promethius Quoroyo Gildersleve Mahatma Moriajib Mattesumium Matilda Maria Cecila Prozelli Motsorelli Puchini Alfred Erasmus Nobelius Scarlotta Newman

43 string names[5]; // names is a reference string *nameptrs[5]; // nameptrs points to a pointer array John Jacob Jinglehiemer Schmidt Alloitious Promethius Quoroyo Gildersleve Mahatma Moriajib Mattesumium Matilda Maria Cecila Prozelli Motsorelli Puchini Alfred Erasmus Nobelius Scarlotta Newman nameptr names 0123401234

44 After sorting… John Jacob Jinglehiemer Schmidt Alloitious Promethius Quoroyo Gildersleve Mahatma Moriajib Mattesumium Matilda Maria Cecila Prozelli Motsorelli Puchini Alfred Erasmus Nobelius Scarlotta Newman nameptrs names 0123401234

45 Program… string names[N]; string *nameptrs[N]; for (int n=0; n<N; n++) { cin >> names[n]; nameptrs[n] = &names[n]; } SortByPointer (names, nameptrs); for (int n=0; n<N; n++) cout << *(nameptrs[n]) << endl;

46 void SortByPointer (string names[ ], string *nameptrs[ ]) { int smallest_position; for (int n=0; n<N-1; n++) {smallest_position = FindSmallest (nameptrs, n, N); Swap (nameptrs, n, smallest_position); } We’ll use a Selection Sort…

47 int FindSmallest (string list[ ], int start, int size) { int position; string smallest = list[start]; for (int k=start+1; k<size; k++) if (list[k] < smallest) < 0) { smallest = list[k]; position = k; } return position; } FindSmallest()

48 Swap() void Swap (string *list[ ], int j, int k) { string *temp; temp = list[j]; list[j] = list[k]; list[k] = temp; }


Download ppt "CS 1400 Chapters 9, 10 C-strings and Pointers. A few C-string library functions… #include int strcmp (char a[ ], char b[ ]); returns 0 if string a is."

Similar presentations


Ads by Google