6.2 arrays and strings

29
1 6.2 Arrays and Strings Computer Programming and Basic Software Engineering 6. Pointers and Arrays

Upload: debbie

Post on 08-Jan-2016

31 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 6.2  Arrays and Strings

1

6.2 Arrays and Strings

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 2: 6.2  Arrays and Strings

2

What Is an Array?

• 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:

short shortArray[25]; It states that there is a sequence of 25 short integer data. The whole

sequence is named as shortArray

It states that there is a sequence of 25 short integer data. The whole

sequence is named as shortArray

shortArray[0] 000B 000C ... ... 0037 0038 0039 003A

Memory

Variables short shortArray[25]; //declaration

10 0A 21 3A ... ... 20 2A 4B 40

Computer Programming and Basic Software Engineering6. Pointers and Arrays

shortArray[1] shortArray[24]

In consecutive memory

Page 3: 6.2  Arrays and Strings

3

Array Element

• 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

25 short integers

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 4: 6.2  Arrays and Strings

4 Computer Programming and Basic Software Engineering6. Pointers and Arrays

short shortArray[25];

0009 000A 000B 000C ... ... 0037 0038 0039 003AAddress

(Hex)

Memory

Variables short shortArray[25];

10 0A 21 3A ... ... 20 2A 4B 40

• So shortArray[0] = 0x100A;// 4106 in deciaml

shortArray[1] = 0x213A;// 8506 in decimal

:

shortArray[23] = 0x202A;

shortArray[24] = 0x4B40;

Declaration

Assignment statements

Page 5: 6.2  Arrays and Strings

5

#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

The kind of mistake people often make

Computer Programming and Basic Software Engineering6. Pointers and Arrays

No myArray[5] !!! Do not try to use myArray[5], result unpredictable

No myArray[5] !!! Do not try to use myArray[5], result unpredictable

Page 6: 6.2  Arrays and Strings

6

Initializing 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

IntegerArray declares itself to have 5 integers

AnotherArray requests the memory space in stack just enough to hold the

data defined in the list

AnotherArray requests the memory space in stack just enough to hold the

data defined in the listBiggerArray declares itself to have 5 integers but only the first 2 of them

are initialized. The others are 0.It is different from :

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 IncorrectArray[2] = {10,20,30};

Computer Programming and Basic Software Engineering6. Pointers and Arrays

int a[5]; NOT the same as int a[5]={};

int BiggerArray[] = {10,20};

Page 7: 6.2  Arrays and Strings

7

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 objectsint i;for (i=0; i<5; i++) cout << Litter[i].GetAge() << endl;

To find out which CATTo find out which CAT Call GetAge() of that CATCall GetAge() of that CAT

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 8: 6.2  Arrays and Strings

8

Multidimensional Array• It is possible to have an array of more than 1 dimension

Two-dimensional arrayA Chess Board

Two-dimensional arrayA Chess Board

int Board[8][8];

• A 2-dimensional array can be declared as

• Each element can be written or read as

Board[5][3] = 0;int number = Board[5][3];// number = 0

0 1 2 3 4 5 6 7

76543210

0

Computer Programming and Basic Software Engineering6. Pointers and Arrays

64 integers

Page 9: 6.2  Arrays and Strings

9

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

0 0

1 2

4 6

7 2

4 4

0 1

4

3

2

1

0

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 10: 6.2  Arrays and Strings

10

Array and Pointer• 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 = 10b = *(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

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 11: 6.2  Arrays and Strings

11

0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address

The Stack

SomeArray[5]

10 20 30 40

Computer Programming and Basic Software Engineering6. Pointers and Arrays

50

x = *SomeArray; will be internally converted to

x = SomeArray[0]; // x = 10

px = SomeArray; will be internally converted to

px = &(SomeArray[0]); // px = 0104

x = *SomeArray; will be internally converted to

x = SomeArray[0]; // x = 10

px = SomeArray; will be internally converted to

px = &(SomeArray[0]); // px = 0104

• There is NOT a memory location to store the pointer SomeArray. Everything is done by an internal conversion

Page 12: 6.2  Arrays and Strings

12 Computer Programming and Basic Software Engineering6. Pointers and Arrays

• A variable declared as a pointer can also be used as an arrayint SomeArray[5] = {10,11,12,13,14};int *pSomePointer = SomeArray; // It is a pointer but will

// later be used as arraycout << pSomePointer[0] << endl; // number 10 will be showncout << pSomePointer[1] << endl; // number 11 will be showncout << pSomePointer[2] << endl; // number 12 will be showncout << pSomePointer[3] << endl; // number 13 will be showncout << pSomePointer[4] << endl; // number 14 will be shown

0100 0104 0108 010c 0110 0114 0118 011c 0120 0124Address

The stack

pSomePointer = 0104

10 11 12 13 14

SomeArray[5]

SomeArray[1] and pSomePointer[1] are exactly the same.

Page 13: 6.2  Arrays and Strings

13

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.

Computer Programming and Basic Software Engineering6. Pointers and Arrays

The array itself is still in the stack.

Page 14: 6.2  Arrays and Strings

14

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

}

Creating 500 CATs may use up all

memory in the stack

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

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

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

To access member of a particular CAT, use the corresponding pointer

in the array

Computer Programming and Basic Software Engineering

Page 15: 6.2  Arrays and Strings

15

Free Storeor

the heap

Global Name SpaceCode SpaceThe Stack

CAT 0 CAT 1

CAT 2

CAT 499

...

Array of Pointers

An array of pointers called Family is kept to point to

different elements in Free Store

An array of pointers called Family is kept to point to

different elements in Free Store

Computer Programming and Basic Software Engineering6. Pointers and Arrays

(*Family[0])

Page 16: 6.2  Arrays and Strings

16

Pointer of Array • 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.

CAT *Family = new CAT[500];

int a = 0, b=0;(Family+255)->SetAge(10);a = (Family+255)->GetAge();// a = 10b = Family[255].GetAge(); // b = 10

Family is the pointer of array and points to Family[0] in

Free Store

Family is the pointer of array and points to Family[0] in

Free Store

Individual element of the array of the CAT objects

can be accessed by pointer arithmetic

Individual element of the array of the CAT objects

can be accessed by pointer arithmetic

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 17: 6.2  Arrays and Strings

17

Pointer of Array

Free Storeor

the heap

Global Name SpaceCode SpaceThe Stack

CAT 0 CAT 1 ... CAT 499

A pointer Family is kept to point to the beginning memory location of an array

of CAT objects in Free Store

A pointer Family is kept to point to the beginning memory location of an array

of CAT objects in Free Store

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Family[0] Family[499]

Page 18: 6.2  Arrays and Strings

18

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

Arrays created in Free Store can also be deleted

The [] symbol after delete lets the system know the whole array is to be deleted

The [] symbol after delete lets the system know the whole array is to be deleted

Computer Programming and Basic Software Engineering

Page 19: 6.2  Arrays and Strings

19

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++?

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Page 20: 6.2  Arrays and Strings

20 Computer Programming and Basic Software Engineering6. 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.

Page 21: 6.2  Arrays and Strings

21

String - char Arrays • A string is an array of characters

char Greeting[] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'};

• A string can be simply initialized as follows:

The null character represents the end of string; it must be added.

The null character represents the end of string; it must be added.

• However, this method can easily introduce error

• C++ provides a shorthand that makes use of the double quote " ".

char Greeting[] = {"Hello World"};Totally 12 bytes are

allocated for Greeting.Null character is

automatically generated

Totally 12 bytes are allocated for Greeting.

Null character is automatically generated

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Size of array is 12

The braces can be removed

Page 22: 6.2  Arrays and Strings

22 Computer Programming and Basic Software Engineering6. 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.

Wrong. Greeting2 is a constant pointer; we cannot assign anything to it - See explanation in the next page.

Page 23: 6.2  Arrays and Strings

23 Computer Programming and Basic Software Engineering6. Pointers and Arrays

0100 0101 0102 0103 010a 010b 010c 010dAddress

The Stack

Greeting[12]

'H' 'e' 'l' 'd' '\0''l'…

0200 0201 0202 0203 020a 020b 020c 010dAddress

The Stack ? ? ? ? ??…

Greeting2[12]

Greeting2 = Greeting; Wrong. We try to make Greeting2 = 0101. However, Greeting2 must = 0201 as it is assigned by the OS, and is constant

Wrong. We try to make Greeting2 = 0101. However, Greeting2 must = 0201 as it is assigned by the OS, and is constant

Page 24: 6.2  Arrays and Strings

24 Computer Programming and Basic Software Engineering6. Pointers and Arrays

Very wrong. Greeting2[12] means only the 13th element of Greeting2, not the whole string. Besides, there is no 13th element in Greeting or Greeting2

Very wrong. Greeting2[12] means only the 13th element of Greeting2, not the whole string. Besides, there is no 13th element in Greeting or Greeting2

Greeting2[12] = Greeting[12];

Note: Greeting2[11] = Greeting[11]; is legal, which means assigning the 12th element of Greeting2 with the value of the 12th element of Greeting.

Page 25: 6.2  Arrays and Strings

25

Strcpy() and strncpy() • C++ inherits from C a library of functions for tackling strings

• The two most common ones are strcpy() and strncpy()

#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 String1 to String2Copy String1 to String2

State the definition of strcpy()You may omit this line because it is already included by iostream

State the definition of strcpy()You may omit this line because it is already included by iostream

Computer Programming and Basic Software Engineering6. Pointers and Arrays

ResultResult

Warning: unsafe

Page 26: 6.2  Arrays and Strings

26

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

Strncpy() needs another parameter MaxLength which specifies the maximum

number of data (not including null) to be copied

Strncpy() needs another parameter MaxLength which specifies the maximum

number of data (not including null) to be copied

State the definition of strncpy()State the definition of strncpy()

Computer Programming and Basic Software Engineering6. Pointers and Arrays Warning: unsafe

Page 27: 6.2  Arrays and Strings

27

Exercise 6.2c

a. Write a program that creates an array of 3 objects of the class ACCOUNT in the free store.

b.Ask the user to input three names and save to each element of the array

c. Read the content of each element in the array and display on the screen.

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

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Pointer of array

Page 28: 6.2  Arrays and Strings

28 Computer Programming and Basic Software Engineering6. Pointers and Arrays

A few more library functions• To measure the

length of a string, the function strlen() is useful

• To combine two strings into one, we can use the function strcat().

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

Convert an integer into a string

Convert an integer into a string

Set decimal

Append a string

5 warnings

Page 29: 6.2  Arrays and Strings

29 Computer Programming and Basic Software Engineering6. 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;}

Syntax:int strcmp(string1, string2)Return 0 if string1 is the same as string2; otherwise returns a +ve or ve number.

Syntax:int strcmp(string1, string2)Return 0 if string1 is the same as string2; otherwise returns a +ve or ve number.

Get one line of text (including the spaces in between)

No warning