1 / 29

6.2 Arrays and Strings

Computer Programming and Basic Software Engineering. 6. Pointers and Arrays. 6.2 Arrays and Strings. Computer Programming and Basic Software Engineering. What Is an Array?. 6. Pointers and Arrays. In consecutive memory.

debbie
Download Presentation

6.2 Arrays and 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. Computer Programming and Basic Software Engineering 6. Pointers and Arrays 6.2 Arrays and Strings

  2. Computer Programming and Basic Software Engineering What Is an Array? 6. Pointers and Arrays In consecutive memory • An array consists of a collection of data storage locations, each holds the same type of data • An array can be easily declared as follows: It states that there is a sequence of 25 short integer data. The whole sequence is named as shortArray short shortArray[25]; Variables short shortArray[25]; //declaration Memory 10 0A 21 3A ... ... 20 2A 4B 40 000B 000C ... ... 0037 0038 0039 003A shortArray[0] shortArray[1] shortArray[24]

  3. Computer Programming and Basic Software Engineering Array Element 6. Pointers and Arrays • In an array, an array element is referred to by indicating its index • The first element has index 0, and then 1, … • Hence shortArray[0] is the first element • shortArray[1] is the second element • : • shortArray[24] is the last element • No shortArray[25]!!! • Do not try to use shortArray[25], result unpredictable. 25 short integers

  4. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Declaration short shortArray[25]; Variables short shortArray[25]; Memory 10 0A 21 3A ... ... 20 2A 4B 40 Address (Hex) 0009 000A 000B 000C ... ... 0037 0038 0039 003A • So shortArray[0]= 0x100A;// 4106 in deciaml • shortArray[1]= 0x213A;// 8506 in decimal • : • shortArray[23] = 0x202A; • shortArray[24] = 0x4B40; Assignment statements

  5. NomyArray[5] !!! Do not try to use myArray[5], result unpredictable Computer Programming and Basic Software Engineering 6. Pointers and Arrays #include <iostream> using namespace std; int main() { int myArray[5],i; for (i=0; i<=5; i++) myArray[i] = 20; for (i=0; i<5; i++) cout << myArray[i] << endl; return 0; } The kind of mistake people often make

  6. Computer Programming and Basic Software Engineering Initializing Arrays 6. Pointers and Arrays • An array can be initialized during declaration int IntegerArray[5] = {10,20,30,40,50}; int AnotherArray[] = {50,40,30,20,10}; int BiggerArray[5] = {10,20}; IntegerArray declares itself to have 5 integers AnotherArray requests the memory space in stack just enough to hold the data defined in the list BiggerArray declares itself to have 5 integers but only the first 2 of them are initialized. The others are 0. It is different from : int a[5]; NOT the same as int a[5]={}; int BiggerArray[] = {10,20}; int IncorrectArray[2] = {10,20,30};

  7. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Array of Objects • Any object can be stored in an array • Accessing member data in an array of objects is a two-step process • Identify the member of array by [] • Access the member by . CAT Litter[5]; //Litter[0] - Litter[4] are 5 objects int i; for (i=0; i<5; i++) cout << Litter[i].GetAge() << endl; To find out which CAT Call GetAge() of that CAT

  8. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Multidimensional Array • It is possible to have an array of more than 1 dimension 7 6 5 4 3 2 1 0 • A 2-dimensional array can be declared as 0 64 integers int Board[8][8]; • Each element can be written or read as 0 1 2 3 4 5 6 7 Board[5][3] = 0; int number = Board[5][3]; // number = 0 Two-dimensional array A Chess Board

  9. Computer Programming and Basic Software Engineering Initialize Multidimensional Arrays 6. Pointers and Arrays • Multidimensional Arrays can also be initialized during declaration int SomeArray[5][2] = { {0,0},{1,2},{4,6},{7,2},{4,4}}; int AnotherArray[5][2] = {0,0,1,2,4,6,7,2,4,4}; 4 3 2 1 0 4 4 7 2 4 6 1 2 0 0 0 1

  10. Computer Programming and Basic Software Engineering Array and Pointer 6. Pointers and Arrays • C++ allows the flexibility for user to use Array and Pointer interchangeably • The name of an array is a constant pointer pointing to the first element of the array int a,b; int SomeArray[5] = {10,20,30,40,50}; a = *SomeArray; // a = 10 b = *(SomeArray+1);// b = 20, pointer arithmetic • Compiler does all the calculation • SomeArray+1 does not add 1 to SomeArray but add 4 (1 integer needs 4 bytes for storage) and point to the next element in the array

  11. Computer Programming and Basic Software Engineering 6. Pointers and Arrays SomeArray[5] The Stack 10 20 30 40 50 Address 0100 0104 0108 010c 0110 0114 0118 011c 0120 0124 • There is NOT a memory location to store the pointer SomeArray. Everything is done by an internal conversion x = *SomeArray; will be internally converted to x = SomeArray[0]; // x = 10 px = SomeArray; will be internally converted to px = &(SomeArray[0]); // px = 0104

  12. Computer Programming and Basic Software Engineering 6. Pointers and Arrays • A variable declared as a pointer can also be used as an array int SomeArray[5] = {10,11,12,13,14}; int *pSomePointer = SomeArray; // It is a pointer but will // later be used as array cout << pSomePointer[0] << endl; // number 10 will be shown cout << pSomePointer[1] << endl; // number 11 will be shown cout << pSomePointer[2] << endl; // number 12 will be shown cout << pSomePointer[3] << endl; // number 13 will be shown cout << pSomePointer[4] << endl; // number 14 will be shown SomeArray[5] The stack 10 11 12 13 14 Address 0100 0104 0108 010c 0110 0114 0118 011c 0120 0124 SomeArray[1] and pSomePointer[1] are exactly the same. pSomePointer = 0104

  13. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Array of Pointers • So far the arrays are declared to store data in stack • Usually the memory space of stack is very small • If a large array is required, it is better to store the elements of arrays in Free Store • In this case, for every element in an array, a pointer is assigned to indicate its location in Free Store • This becomes an array of pointers. The array itself is still in the stack.

  14. Computer Programming and Basic Software Engineering #include <iostream> using namespace std; class CAT {public: CAT() {itsAge = 1;} ~CAT() {} int GetAge() const {return itsAge;} void SetAge(int age) {itsAge = age;} private: int itsAge; }; int main() { CAT *Family[500]; int i; for (i=0; i<500; i++) { Family[i] = new CAT; } Family[255]->SetAge(1); for (i=0; i<500; i++) { delete Family[i]; } return 0; } 6. Pointers and Arrays Creating 500 CATs may use up all memory in the stack Hence only an array of 500 pointers of CAT are created in the stack Each CAT object is located in the Free Store by the keyword new To access member of a particular CAT, use the corresponding pointer in the array

  15. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Array of Pointers Free Store or the heap CAT 2 (*Family[0]) CAT 0 CAT 1 An array of pointers called Family is kept to point to different elements in Free Store CAT 499 ... The Stack Code Space Global Name Space

  16. Computer Programming and Basic Software Engineering Pointer of Array 6. Pointers and Arrays • If one feels that 500 pointers in the previous example are still too many, we can put the whole array into Free Store • Hence one pointer is enough to point to the Array itself but not an individual element • This becomes a pointer of array. Family is the pointer of array and points to Family[0] in Free Store CAT *Family = new CAT[500]; Individual element of the array of the CATobjects can be accessed by pointer arithmetic int a = 0, b=0; (Family+255)->SetAge(10); a = (Family+255)->GetAge();// a = 10 b = Family[255].GetAge(); // b = 10

  17. Computer Programming and Basic Software Engineering Pointer of Array 6. Pointers and Arrays Free Store or the heap Family[0] Family[499] CAT 0 CAT 1 ... CAT 499 A pointer Family is kept to point to the beginning memory location of an array of CATobjects in Free Store The Stack Code Space Global Name Space

  18. Computer Programming and Basic Software Engineering 6. Pointers and Arrays #include <iostream> using namespace std; class CAT {public: CAT() {itsAge = 1;} ~CAT(){;} int GetAge() const {return itsAge;} void SetAge(int age) {itsAge = age;} private: int itsAge; }; int main() { CAT *Family = new CAT[10]; for (int i=0; i<10; i++) { Family[i].SetAge(2*i+1); cout <<' '<< Family[i].GetAge(); } delete [] Family; return 0; } Arrays created in Free Store can also be deleted The [] symbol after delete lets the system know the whole array is to be deleted

  19. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Exercise 6.2 • Based on the program in the last page, add a destructor to CAT such that when it is called, the age of the cat will be shown on the screen. • How many times the destructor will be called when the “delete [] Family;” statement is executed? Why? • What will happen if we use the statement “delete Family” instead? Can it be executed in Visual C++?

  20. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Exercise 6.2b • Modify the program in Ex.6.2 such that the “Array of Pointers” approach is used to define the 10 objects of CAT in the heap. Make sure your program will not introduce memory leaks.

  21. Computer Programming and Basic Software Engineering 6. Pointers and Arrays The null character represents the end of string; it must be added. String - char Arrays • A string is an array of characters • A string can be simply initialized as follows: char Greeting[] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; Size of array is 12 • However, this method can easily introduce error • C++ provides a shorthand that makes use of the double quote " ". Totally 12 bytes are allocated for Greeting. Null character is automatically generated char Greeting[] = {"Hello World"}; The braces can be removed

  22. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Copying String • We often need to copy string from one character array to another character array char Greeting[12] = {"Hello World"}; char Greeting2[12]; • Common errors: Greeting2 = Greeting; Wrong. Greeting2 is a constant pointer; we cannot assign anything to it - See explanation in the next page.

  23. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Greeting[12] The Stack … 'H' 'e' 'l' 'l' 'd' '\0' Address 0100 0101 0102 0103 010a 010b 010c 010d Greeting2[12] The Stack ? ? ? … ? ? ? Address 0200 0201 0202 0203 020a 020b 020c 010d Wrong. We try to make Greeting2 = 0101. However, Greeting2 must = 0201 as it is assigned by the OS, and is constant Greeting2 = Greeting;

  24. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Greeting2[12] = Greeting[12]; Very wrong. Greeting2[12] means only the 13th element of Greeting2, not the whole string. Besides, there is no 13thelement in Greeting or Greeting2 Note: Greeting2[11] = Greeting[11]; is legal, which means assigning the 12th element of Greeting2 with the value of the 12th element of Greeting.

  25. Result Computer Programming and Basic Software Engineering 6. Pointers and Arrays Warning: unsafe Strcpy() and strncpy() • C++ inherits from C a library of functions for tackling strings • The two most common ones are strcpy() and strncpy() State the definition of strcpy() You may omit this line because it is already included by iostream #include <iostream> #include <string.h> using namespace std; int main() { char String1[] = {"Copy String1 to String2"}; char String2[80]; strcpy(String2,String1); cout << "String1: " << String1 << endl; cout << "String2: " << String2 << endl; return 0; } Copy String1to String2

  26. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Warning: unsafe • Strcpy() will overwrite past the end of the destination if the source were larger than the destination, damaging other data • To solve the problem, strncpy() can be used #include <iostream> #include <string.h> using namespace std; int main() { const int MaxLength = 80; //MaxLength > strlen(String1) = 23 char String1[] = "Copy String1 to String2"; char String2[MaxLength+1]; //Initialize String2 if MaxLength<=23 strncpy(String2,String1,MaxLength); cout << "String1: " << String1 << endl; cout << "String2: " << String2 << endl; return 0; } State the definition of strncpy() Strncpy() needs another parameter MaxLengthwhich specifies the maximum number of data (not including null) to be copied

  27. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Exercise 6.2c class ACCOUNT { public: void writename(char nm[]); char * readname(); private: char name[80]; }; void ACCOUNT::writename(char nm[]) { strncpy(name,nm,79); } char * ACCOUNT::readname() { return name; } • Write a program that creates an array of 3 objects of the class ACCOUNT in the free store. • Ask the user to input three names and save to each element of the array • Read the content of each element in the array and display on the screen. Pointer of array

  28. Computer Programming and Basic Software Engineering A few more library functions 6. Pointers and Arrays #include <iostream> #include <string.h> using namespace std; int main() { char String1[100]; cout << "Please enter a word: "; cin >> String1; char String2[] = " has "; char String3[5]; char String4[] = " characters."; itoa(strlen(String1),String3,10); strcat(String1,String2);//ret String1 strcat(String1,String3); strcat(String1,String4); cout << String1 << endl; return 0; } • To measure the length of a string, the function strlen() is useful • To combine two strings into one, we can use the function strcat(). Convert an integer into a string Set decimal Append a string 5 warnings

  29. Computer Programming and Basic Software Engineering Get one line of text (including the spaces in between) 6. Pointers and Arrays • We can compare if two strings are the same using the function strcmp(). #include <iostream> #include <string.h> using namespace std; int main() { char String1[100]; cout << "Please enter your name: "; cin.getline(String1,100); char String2[] = "Dr F Leung"; if (strcmp(String1, String2)==0) cout << "Welcome Dr Leung.\n"; else cout << "Login incorrect.\n"; return 0; } No warning Syntax: int strcmp(string1, string2) Return 0 if string1 is the same as string2; otherwise returns a +ve or ve number.

More Related