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.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
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.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Pointers in C Rohit Khokher
Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Chapter 10.
CS 1400 Chapter 10 Strings. Character testing library #include bool isalpha (char c); bool isalnum (char c); bool isdigit (char c); bool islower (char.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
CS 1400 Apr 18, 2007 Chapter 10 Strings. Character testing library #include bool isalpha (char c); bool isalnum (char c); bool isdigit (char c); bool.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
CS 1400 March 30, 2007 Chapter 8 Searching and Sorting.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
CS 1400 Apr 6, 2007 Chapters 9, 10 C-strings and Pointers.
CS 1400 Chapter 7 ARRAYS. Array variables Simple variables can hold single values int x;// x can hold one integer float y; // y can hold one float Array.
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.
CS Nov 2006 C-strings.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Chapter 8 Arrays and Strings
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
CS 1400 Chapter 7 ARRAYS. Array variables Simple variables can hold single values int x;// x can hold one integer float y; // y can hold one float Array.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Functions Why we use functions C library functions Creating our own functions.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
STARTING OUT WITH STARTING OUT WITH Class 9 Honors.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Dynamic memory allocation and Pointers Lecture 4.
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.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Characters, Strings, And The string Class Chapter 10.
Review 1 List Data Structure List operations List Implementation Array Linked List.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Pointers and Dynamic Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
Standard Version of Starting Out with C++, 4th Edition
Object Oriented Programming COP3330 / CGS5409
Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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 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.

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.

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.

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[ ]);

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 ……

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

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; }

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; }

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); }

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); }

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; }

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.

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

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)

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

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;

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;

fptr iptr x400 0x or more commonly diagrammed using arrows… fptr iptr x400 0x a b a b

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”

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

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;

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;

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

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; }

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

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)

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 0x

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

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

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;

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?

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

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.

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]);

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

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

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!

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… …

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

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

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

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

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

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;

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…

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

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