1 / 47

Chapter 7 Pointers and C-Strings

Chapter 7 Pointers and C-Strings. What is a Pointer?.

kailey
Download Presentation

Chapter 7 Pointers and C-Strings

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7 Pointers and C-Strings

  2. What is a Pointer? Pointer variables, simply called pointers, are designed to hold memory addresses as their values. Normally, a variable contains a specific value, e.g., an integer, a floating-point value, and a character. However, a pointer contains the memory address of a variable that in turn contains a specific value.

  3. Declare a Pointer Like any other variables, pointers must be declared before they can be used. To declare a pointer, use the following syntax: dataType *pVarName; Each variable being declared as a pointer must be preceded by an asterisk (*). For example, the following statement declares a pointer variable named pCount that can point to an int varaible. int *pCount, count; Count=5; pCount=&count; Run TestPointer

  4. #include <iostream> using namespace std; int main() { int count = 5; int *pCount = &count; cout << "The address of count is " << &count << endl; cout << "The address of count is " << pCount << endl; cout << "The value of count is " << count << endl; cout << "The value of count is " << *pCount << endl; return 0; }

  5. Dereferencing Referencing a value through a pointer is called indirection. The syntax for referencing a value from a pointer is *pointer For example, you can increase count using count++; // direct reference or (*pCount)++; // indirect reference

  6. Pointer Type A pointer variable is declared with a type such as int, double, etc. You have to assign the address of the variable of the same type. It is a syntax error if the type of the variable does not match the type of the pointer. For example, the following code is wrong. int area = 1; double *pArea = &area; // Wrong

  7. Initializing Pointer Like a local variable, a local pointer is assigned an arbitrary value if you don’t initialize it. A pointer may be initialized to 0, which is a special value for a pointer to indicate that the pointer points to nothing. You should always initialize pointers to prevent errors. Dereferencing a pointer that is not initialized could cause fatal runtime error or it could accidentally modify important data.

  8. Caution You can declare two variables on the same line. For example, the following line declares two int variables: int i = 0, j = 1; Can you declare two pointer variables on the same line as follows? int* pI, pJ; No, this line is equivalent to int *pI, pJ; You have to put Int *p1, *p2;

  9. Passing Arguments by Reference with Pointers There are three ways to pass arguments to a function in C++: pass by value, pass by reference with reference arguments, and pass by reference with pointers. Run TestPointerArgument

  10. #include <iostream> using namespace std; // Swap two variables void swap(int *pValue1, int *pValue2) { // Swap n1 with n2 int temp = *pValue1; *pValue1 = *pValue2; *pValue2 = temp; }

  11. int main() { // Declare and initialize variables int num1 = 1; int num2 = 2; cout << "Before invoking the swap function, num1 is " << num1 << " and num2 is " << num2 << endl; // Invoke the swap function to attempt to swap two variables swap(&num1, &num2); cout << "After invoking the swap function, num1 is " << num1 << " and num2 is " << num2 << endl; return 0; }

  12. Arrays and Pointers Recall that an array variable without a bracket and a subscript actually represents the starting address of the array. In this sense, an array variable is essentially a pointer. Suppose you declare an array of int value as follows: int list[6] = {11, 12, 13, 14, 15, 16};

  13. Array Pointer *(list + 1) is different from *list + 1. The dereference operator (*) has precedence over +. So, *list + 1 adds 1 to the value of the first element in the array, while *(list + 1) dereference the element at address (list + 1) in the array. Run ArrayPointer Run PointerWithIndex

  14. #include <iostream> using namespace std; int main() { int list[6] = {11, 12, 13, 14, 15, 16}; for (int i = 0; i < 6; i++) cout << "address: " << (list + i) << " value: " << *(list + i) << " " << " value: " << list[i] << endl; return 0; }

  15. Using const with Pointers You learned how to declare a constant using the const keyword. A constant cannot be changed once it is declared. You can declare a constant pointer. For example, see the following code: double radius = 5; double * const pValue = &radius; ConstParameter Run

  16. #include <iostream> using namespace std; void printArray(int const *, const int); // function prototype int main() { int list[6] = {11, 12, 13, 14, 15, 16}; printArray(list, 6); return 0; } void printArray(int const *list, const int size) { for (inti = 0; i < size; i++) cout << list[i] << " "; }

  17. Returning Pointers from Functions You can use pointers as parameters in a function. Can you return a pointer from a function? The answer is yes. WrongReverse Run

  18. #include <iostream> using namespace std; int * reverse(int const * list, const int size) { int result[size]; for (int i = 0, j = size - 1; i < size; i++, j--) { result[j] = list[i]; } return result; } void printArray(int const *list, const int size) { for (int i = 0; i < size; i++) cout << list[i] << " "; } int main() { int list[] = {1, 2, 3, 4, 5, 6}; int *pList = reverse(list, 6); printArray(pList, 6); return 0; } WrongReverse

  19. Dynamic Memory Allocation • A dynamic variableis a variable that is stored in the heap, outside the data and stack segments, that may change size during runtime or may even disappear for good. In fact if we do not allocate a certain amount of memory to store its contents, it will never exist. • For example consider the next declaration : • double *dp; • dp = new double; • Remember one thing - dynamic variables are never initialized by the compiler. Therefore it is good practice to first assign them a value, or your calculations may not come out right. There are two ways of doing this : • dp = new double; *dp = a; or • dp = new double(a);

  20. Consider this line of code : double *dp = new double(3.1415); Now consider you have decided to erase the dynamic variable for good from the heap. Use the delete operator to achieve this : delete dp; Notice that while we have freed 8 bytes of memory - which is sizeof(double) - the dp pointer was not erased. It still exists in the data or stack segment of the application and we may use it to initialize another dynamic variable.

  21. C++ also provides the possibility to allocate an entire array in the heap, keeping a pointer to its first element. Again we use the new operator but mention the size of the array in square brackets : int *table; table = new int[100]; Arrays allocated in the heap are similar to those allocated in the data or stack segments, so we may access an arbitrary element using the indexing operator []. For example the next loop initializes each element of the array to zero : for (int i = 0; i < 100; ++i) table[i] = 0; To erase a heap-allocated array we will use the delete operator, but this time add a pair of square brackets so that the compiler can differentiate it from an ordinary dynamic variable. delete [] table;

  22. Dynamic Memory Allocation • Enables you to allocate persistence storage dynamically at run time using new operator • int *pvalue = new int; • You can access the memory through a pointer • int *list = new int[10]; • C++ allocate the local variable in the stack. • With new operator the memory area is called a heap and remains available until you explicitly free it or program terminates • delete keyword can be used to free the memory • delete pvalue; delete [] list;

  23. #include <iostream> using namespace std; int * reverse(const int * list, int size) { int *result = new int[size]; for (int i = 0, j = size - 1; i < size; i++, j--) { result[j] = list[i]; } return result; } void printArray(const int *list, int size) { for (int i = 0; i < size; i++) cout << list[i] << " "; } int main() { int list[] = {1, 2, 3, 4, 5, 6}; int *pList = reverse(list, 6); printArray(pList, 6); return 0; } CorrectReverse

  24. Case Studies: Counting the Occurrences of Each Letter • Generate 100 lowercase letters randomly and assign to an array of characters. • Count the occurrence of each letter in the array. CountLettersInArray Run

  25. #include <iostream> #include "RandomCharacter.h" using namespace std; const int NUMBER_OF_LETTERS = 100; char * createArray(); void displayArray(char []); int * countLetters(char []); void displayCounts(int []); int main() { // Declare and create an array char * chars = createArray(); // Display the array cout << "The lowercase letters are: " << endl; displayArray(chars); // Count the occurrences of each letter int * counts = countLetters(chars); // Display counts cout << endl; cout << "The occurrences of each letter are: " << endl; displayCounts(counts); return 0; } CountLettersInArray

  26. char * createArray() { // Declare an array of characters and create it char *chars = new char[NUMBER_OF_LETTERS]; // Create lowercase letters randomly and assign // them to the array srand(time(0)); for (int i = 0; i < NUMBER_OF_LETTERS; i++) chars[i] = getRandomLowerCaseLetter(); // Return the array return chars; }

  27. // Display the array of characters void displayArray(char chars[]) { // Display the characters in the array 20 on each line for (int i = 0; i < NUMBER_OF_LETTERS; i++) { if ((i + 1) % 20 == 0) cout << chars[i] << " " << endl; else cout << chars[i] << " "; } }

  28. // Count the occurrences of each letter int * countLetters(char chars[]) { // Declare and create an array of 26 int int *counts = new int[26]; // Initialize the array for (int i = 0; i < 26; i++) counts[i] = 0; // For each lowercase letter in the array, count it for (int i = 0; i < NUMBER_OF_LETTERS; i++) counts[chars[i] - 'a'] ++; return counts; }

  29. // Display counts void displayCounts(int counts[]) { for (int i = 0; i < 26; i++) { if ((i + 1) % 10 == 0) cout << counts[i] << " " << static_cast<char>(i + 'a') << endl; else cout << counts[i] << " " << static_cast<char>(i + 'a') << " "; } }

  30. Characters and C-Strings Strings are used often in programming. You have used string literals. A string is a sequence of characters. There are two ways to process strings in C++. One way is to treat strings as arrays of characters. This is known as pointer-based strings or C-strings. The other way is to process strings using the string class. The string class will be introduced in §9.14. This section introduces pointer-based strings.

  31. Character Test Functions

  32. Case Conversion Functions

  33. #include <iostream> using namespace std; int main() { cout << "Enter a character: "; char ch; cin >> ch; cout << "You entered " << ch << endl; if (islower(ch)) { cout << "It is a lowercase letter " << endl; cout << "Its equivalent uppercase letter is " << static_cast<char>(toupper(ch)) << endl; } else if (isupper(ch)) { cout << "It is an uppercase letter " << endl; cout << "Its equivalent lowercase letter is " << static_cast<char>(tolower(ch)) << endl; } else if (isdigit(ch)) { cout << "It is a digit character " << endl; } return 0;} CharacterFunctions

  34. Storing and Accessing Strings A pointer-based string in C++ is an array of characters ending in the null terminator ('\0'), which indicates where a string terminates in memory. An array can be accessed via a pointer. So a string can also be accessed via a pointer, which points to the first character in the string. So you can declare a string variable using an array or a pointer. For example, the following two declarations are both fine: char city[7] = "Dallas"; // Option 1 char *pCity = "Dallas"; // Option 2

  35. Pointer Syntax You can access city or pCity using the array syntax or pointer syntax. For example, cout << city[1] << endl; cout << *(city + 1) << endl; cout << pCity[1] << endl; cout << *(pCity + 1) << endl; each displays character a (the second element in the string).

  36. Reading Strings You can read a string from the keyboard using the cin object. For example, see the following code: cout << "Enter a city: "; cin >> city; // read to array city cout << "You entered " << city << endl;

  37. Reading Strings Using getline C++ provides the cin.getline function in the iostream header file, which reads a string into an array. The syntax of the function is: cin.getline(char array[], int size, char delimitChar) The function stops reading characters when the delimiter character is encountered or when the size - 1 number of characters are read. The last character in the array is reserved for the null terminator ('\0'). If the delimiter is encountered, it is read, but not stored in the array. The third argument delimitChar has a default value ('\n').

  38. String Functions

  39. String Examples Run CopyString Run CombineString Run CompareString StringConversion Run

  40. #include <iostream> #include <cstring> using namespace std; int main() { char s1[20]; char s2[20] = "Dallas, Texas"; char s3[20] = "AAAAAAAAAA"; strcpy(s1, s2); strncpy(s3, s2, 6); s3[6] = '\0'; // Insert null terminator cout << "The string in s1 is " << s1 << endl; cout << "The string in s2 is " << s2 << endl; cout << "The string in s3 is " << s3 << endl; cout << "The length of string s3 is " << strlen(s3) << endl; return 0;} CopyString

  41. #include <iostream> #include <cstring> using namespace std; int main() { char *s1 = "abcdefg"; char *s2 = "abcdg"; char *s3 = "abcdg"; cout << "strcmp(s1, s2) is " << strcmp(s1, s2) << endl; cout << "strcmp(s2, s1) is " << strcmp(s2, s1) << endl; cout << "strcmp(s2, s3) is " << strcmp(s2, s3) << endl; cout << "strncmp(s1, s2, 3) is " << strncmp(s1, s2, 3) << endl; return 0; } CompareString

  42. #include <iostream> #include <cstring> using namespace std; int main() { char s1[20] = "Dallas"; char s2[20] = "Texas, USA"; char s3[20] = "Dallas"; strcat(strcat(s1, ", "), s2); strncat(strcat(s3, ", "), s2, 5); cout << "The string in s1 is " << s1 << endl; cout << "The string in s2 is " << s2 << endl; cout << "The string in s3 is " << s3 << endl; cout << "The length of string s1 is " << strlen(s1) << endl; cout << "The length of string s3 is " << strlen(s3) << endl; return 0; } CombineString

  43. Obtaining Substrings Often it is useful to obtain a substring from a string. But there is no such function in C++. You can develop your own function for extracting substrings. The header of the function can be specified as: char * substring(char *s, int start, int end) Substring.h TestSubstring Run

  44. #include <iostream> #include "Substring.h" using namespace std; int main() { char *s = "Atlanta, Georgia"; cout << substring(s, 0, 7); return 0; } char * substring(const char * const s, int start, int end) { char * pNewString = new char[end - start + 1 + 1]; int j = 0; for (int i = start; i < end; i++, j++) { pNewString[j] = s[i]; } pNewString[j] = '\0'; // Set a null terminator return pNewString; }

  45. Checking Palindromes A string is a palindrome if it reads the same forward andbackward. The words“mom,”“dad,”and “noon,” for example, are all palindromes. CheckPalindrome Run

  46. #include <iostream> #include <cstring> using namespace std; // Check if a string is a palindrome bool isPalindrome(const char *); int main() { // Prompt the user to enter a string cout << "Enter a string: "; char s[80]; cin.getline(s, 80); if (isPalindrome(s)) cout << s << " is a palindrome" << endl; else cout << s << " is not a palindrome" << endl; return 0; } boolisPalindrome(const char * const s) { // The index of the first character in the string int low = 0; // The index of the last character in the string int high = strlen(s) - 1; while (low < high) { if (s[low] != s[high]) return false; // Not a palindrome low++; high--; } return true; // The string is a palindrome }

  47. Assignment • Review questions: All the questions. • Programming Exercises: 1, 4, 5, 6, 7, 9, 12, 14, 17, 18, 19.

More Related