Presentation is loading. Please wait.

Presentation is loading. Please wait.

送孟浩然之廣陵 ~ 李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧山盡, 唯見長江天際流。.

Similar presentations


Presentation on theme: "送孟浩然之廣陵 ~ 李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧山盡, 唯見長江天際流。."— Presentation transcript:

1 送孟浩然之廣陵 ~ 李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧山盡, 唯見長江天際流。

2 Chapter 4 Arrays, Strings, and Pointers

3 Checking Duplicate Input
// ex3_0.cpp : Checking duplicate input #include <iostream> using std::cin; using std::cout; int main() { int a1, a2, a3; cin >> a1 >> a2 >> a3; if (a1 == a2 || a1 == a3 || a2 == a3) cout << "Duplicate.\n"; return 0; }

4 If We Have 5 Numbers to Compare
// ex3_0a.cpp : Checking duplicate input #include <iostream> using std::cin; using std::cout; int main() { int a1, a2, a3, a4, a5; cin >> a1 >> a2 >> a3 >> a4 >> a5; if (a1 == a2 || a1 == a3 || a1 == a4 || a1 == a5 || a2 == a3 || a2 == a4 || a2 == a5 || a3 == a4 || a3 == a5 || a4 == a5) cout << "Duplicate.\n"; return 0; }

5 Example: Coin Tossing A coin has two sides – Head/Tail
0/1 Repeat tossing the coin 20 times Count the occurrences of Head and Tail, respectively.

6 Sample Code (coin_tossing.cpp)
int main() { int head = 0; int tail = 0; int i; // srand((unsigned) time(NULL)); for (int k = 0; k < 20; k++ ) i = rand() % 2; // coin tossing if (i == 0) // 0 for Head; 1 for Tail ++head; cout << "Head" << endl; } else ++tail; cout << "Tail" << endl; cout << "There are totally " << head << " Heads and " << tail << " Tails.\n"; return 0;

7 The value of rand() % 6 is 0 ~ 5
Dice Rolling int main() { int p1 = 0; int p2 = 0; int p3 = 0; int p4 = 0; int p5 = 0; int p6 = 0; int i; for (int k = 0; k < 20; k++ ) i = rand() % 6 + 1; switch (i) case 1: ++p1; break; case 2: ++p2; case 3: ++p3; The value of rand() % 6 is 0 ~ 5 case 4: ++p4; break; case 5: ++p5; case 6: ++p6; } cout << "Statistics of pips:" << endl; cout << "1: " << p1 << endl; cout << "2: " << p2 << endl; cout << "3: " << p3 << endl; cout << "4: " << p4 << endl; cout << "5: " << p5 << endl; cout << "6: " << p6 << endl; return 0;

8 Using An Array (dice1.cpp)
int main() { int p[6] = { 0 }; int i; for (int k = 0; k < 20; k++ ) i = rand() % 6; // The value of rand() % 6 is 0 ~ 5 ++p[i]; } cout << "Statistics of pips:" << endl; for (i=0; i<6; i++) cout << i + 1 << ": " << p[i] << endl; return 0; 19 fewer lines of code

9 Arrays To reference several data elements of a particular type with a single variable name. Individual items in an array are specified by an index value. The first having the index number 0. The last having the index number N-1. All the elements of an array are stored in a contiguous block of memory.

10 Duplication Check Using Arrays
// ex3_0b.cpp #include <iostream> using std::cout; using std::cin; int main() { int i, j; bool duplicate = false; int a[10]; for (i=0; i<10; i++) cin >> a[i]; for (j=0; j<10; j++) if (a[i]==a[j] && i!=j) duplicate = true; if (duplicate) cout << "Duplicate.\n"; return 0; }

11 Figure 4-1 (P.130)

12 Declaring Arrays int height[6]; double horsepower[10];
Because each int value occupies 4 bytes in memory, the whole array requires 24 bytes. double horsepower[10]; Q: How many bytes will be required for this array? const int MAX(20); double miles [ MAX ]; P.58 sizeof(double) = 8

13 Using Arrays Ex4_01.cpp on P.131 cin >> gas[count];
cin >> miles[count]; cout << (miles[i] – miles[i-1])/gas[i]; If you use illegal index values, there are no warnings produced either by the compiler or at run-time. MAX=20, so index values 0~19 are legal. gas[-1] and gas[30] are illegal

14 Initializing Arrays Ex4_02.cpp on P.134
To initialize an array in its declaration, you put the initializing values separated by commas between braces int apple = 10; int miles[5] = {1019, 1650, 2197, 2749, 3273}; The array elements for which you didn’t provide an initial value is initialized with zero. This isn’t the same as supplying no initializing list. Without an initializing list, the array elements contain junk values. Ex4_02.cpp on P.134

15 Initializing Arrays (2)
A convenient way to initialize a whole array to zero is simply to specify a single initializing value as 0. int data[100] = { 0 }; You may also omit the dimension of an array of numeric type: int value[] = { 2, 3, 4 } ; The number of elements in the array is determined automatically.

16 Exercise: Dice + Stars 1: 3 *** 2: 5 ***** 3: 5 ***** 4: 3 *** 5: 1 * 6: 3 ***

17 dice1-bar.exe

18 Exercise: Two Dices

19 Multidimensional Array (P.136)
An array can also have more than one index value, in which case it is called a multidimensional array. double matrix[3][7]; matrix[2][4] = 10.7 Note that a two-dimensional array in native C++ is essentially a one-dimensional array of one-dimensional array.

20 Initializing Multidimensional Arrays
Initialize a two-dimensional array int data [2][4] = { { 1, 2, 3, 5}, { 7, 11, 13, 17} }; You can omit initializing values in any row { 1, 2, }, { 7, }

21 Initializing Multidimensional Arrays (2)
Initializing a whole array with zeros. int data[2][4][6] = { 0 }; Storing Multiple Strings (2-dim char array) char stars[][80] = { “Robert Redford”, “Hopalong Cassidy”, “Lassie”, “Slim Pickens”, “Boris Karloff”, “Oliver Hardy” }; Note that you cannot omit both array dimensions. The rightmost dimension(s) must always be defined. int data [][2][2] = { { {1,1}, {1,2} }, { {2,1}, {2,2} } }

22 Sample Code matrix_add.cpp
int main() { const int N = 3; int a[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int b[N][N] = { {10, 20, 30}, {40, 50, 60}, {70, 80, 90} int c[N][N]; int i, j; for (i=0; i<N; i++) // Matrix addition for (j=0; j<N; j++) c[i][j] = a[i][j] + b[i][j]; for (i=0; i<N; i++) // Print out cout << c[i][j] << ' '; cout << endl; } return 0; Sample Code matrix_add.cpp

23 Exercise: Matrix Multiplication

24 Character Arrays and Strings (P.140)
An array of type char is called a character array. It is generally used to store a character string. A string terminates with a null character, which is defined by the escape sequence ‘\0’. It is a byte with all bits as zero.

25 String Input const int MAX(20); char name [MAX];
cin.getline(name, MAX, ‘\n’);

26 String Input (2) It is your responsibility to ensure that the array is large enough for any string you might subsequently want to store. Q: Can the array “char name[20]” store the string “ ”? The maximum number of characters read is MAX-1 (rather than MAX), to allow for the ‘\0’ character to be appended. For a string you get from cin, The ‘\n’ isn’t stored in the input array name

27 String Input (3) You may also use cin to input a string, but please note that the delimiter of cin is whitespaces. Q: If you supply “Albert Einstein”, what will “cin >> name” store into the string name? Ex4_04.cpp on P.142 Counting string characters - strlen() \”

28 Exercise: Caesar Cipher

29 Homework: Running Horse

30 [HW] TETRIS (1) - Seven Shapes

31 Midterm Exam (1) Date: April 1st (Wednesday) Time: 08:30-10:10
Place: H-103 Scope: Chapter 2, 3, 4 Open book. Turn off computers and mobile phones.

32 嫦娥 雲母屏風燭影深, 長河漸落曉星沉。 嫦娥應悔偷靈藥, 碧海青天夜夜心 。 李商隱

33 Some Examples Using Arrays
Sorting Fibonacci Sequence Coin Tossing Decimal to Binary Conversion Binary to Decimal Conversion

34 The puzzle that I posed was...
Suppose a newly-born pair of rabbits, one male, one female, are put in a field. Rabbits are able to mate at the age of one month. So at the end of its second month a female can produce another pair of rabbits. Suppose that our rabbits never die. And the female always produces one new pair (one male, one female) every month from the second month on. The puzzle that I posed was... How many pairs will there be in one year? Source: Suffolk Maths

35 Pairs 1 pair At the end of the first month there is still only one pair

36 Pairs 1 pair 1 pair 2 pairs End first month… only one pair
At the end of the second month the female produces a new pair, so now there are 2 pairs of rabbits 2 pairs

37 Pairs 1 pair 1 pair 2 pairs 3 pairs End first month… only one pair
End second month… 2 pairs of rabbits 2 pairs At the end of the third month, the original female produces a second pair, making 3 pairs in all in the field. 3 pairs

38 Pairs 1 pair 1 pair 2 pairs 3 pairs 5 pairs
End first month… only one pair 1 pair End second month… 2 pairs of rabbits 2 pairs End third month… 3 pairs 3 pairs 5 pairs At the end of the fourth month, the first pair produces yet another new pair, and the female born two months ago produces her first pair of rabbits also, making 5 pairs.

39 Recursive Definition Fibonacci sequence Lucas sequence
F[0] = 0, F[1] = 1, F[n] = F[n-1] + F[n-2] Lucas sequence L[0] = 2, L[1] = 1, L[n] = L[n-1] + L[n-2] You may write a program to verify L[n] == F[n+2] - F[n-2]

40 Expected Result Fibonacci sequence:
Lucas sequence: ========================= L[ 2]= F[ 4]= F[ 0]= == 3 - 0 L[ 3]= F[ 5]= F[ 1]= == 5 - 1 L[ 4]= F[ 6]= F[ 2]= == 8 - 1 L[ 5]= F[ 7]= F[ 3]= == L[ 6]= F[ 8]= F[ 4]= == L[ 7]= F[ 9]= F[ 5]= == L[ 8]= F[10]= F[ 6]= == L[ 9]= F[11]= F[ 7]= == L[10]= F[12]= F[ 8]= == L[11]= F[13]= F[ 9]= == L[12]= F[14]= F[10]= == L[13]= F[15]= F[11]= == L[14]= F[16]= F[12]= == L[15]= F[17]= F[13]= == L[16]= F[18]= F[14]= == L[17]= F[19]= F[15]= ==

41 Sample Code (fibonacci.cpp)
int n = 0; const int M = 20; int L[M] = {2, 1}; int F[M] = {0, 1}; for (n=2; n<M; n++) { L[n] = L[n-1] + L[n-2]; F[n] = F[n-1] + F[n-2]; } cout << "Fibonacci sequence: " << endl; for (n=0; n<M; n++) cout << F[n] << " "; cout << endl; cout << "Lucas sequence: " << endl; cout << L[n] << " "; cout << endl << "=========================" << endl; for (n=2; n<M-2; n++) cout << "L[" << setw(2) << n << "]=" << setw(4) << L[n] << "\t" << "F[" << setw(2) << n+2 << "]=" << setw(4) << F[n+2] << "\t" << "F[" << setw(2) << n-2 << "]=" << setw(3) << F[n-2] << "\t" << L[n] << (L[n]==F[n+2]-F[n-2]?" == ":" != ") << F[n+2] << " - " << F[n-2] << endl; Sample Code (fibonacci.cpp)

42 Decimal to Binary Conversions
dec2bin.cpp Octal dec2oct.cpp How about septenary (七進位)? Hexadecimal dec2hex.cpp dec2hex_v2.cpp

43 Binary to Decimal Conversion
// bin2dec.cpp #include <iostream> using std::endl; using std::cout; using std::cin; int main() { short i; char b[9]; cout << "Please input a binary string -- "; cin >> b; for (i=0; i<8; i++) b[i] -= 48; // '0' = 48 for (i=0; i<=6; i++) b[i+1] = b[i] * 2 + b[i+1]; cout << static_cast<short>(b[7]) << endl; return 0; } '0' '1' 48 49 1

44 Exercise & Homework Exercise: Homework
Improve bin2dec.cpp so that it can accept shorter binary digits such as 1101. Bonus: Users can input binary strings such as “ ” or simply “101”. Invalid input such as “ ” or will be rejected with a warning message. Homework oct2dec.cpp hex2dec.cpp

45 Homework: Drunken Man 座號

46 argc, argv C:\> demo.exe This is a book. There are 5 arguments. 0 - demo.exe 1 - This 2 - is 3 - a 4 - book. #include <iostream> using std::cout; int main(int argc, char* argv[]) { int i; cout << "There are " << argc << " arguments.\n"; for (i=0; i<argc; i++) cout << i << " - " << argv[i] << '\n'; return 0; }

47 red_quotation.cpp Suppose you have a file “test.txt”, whose contents is You know "COLOR_PAIR", so you can write a program to read a text file, and highlight the "strings". This is useful, especially in a "C++" program. After you run “demo test.txt”,

48 Specify Arguments in Visual C++
While you are debugging, you may want to specify the command arguments in Visual C++. Alt-F7 to open the Property Page Configuration Properties – Debugging – Command Arguments.

49 TODO There are many ways you can improve this program:
Check the number of arguments at the command line. Show strings in red, comments in green, keywords (e.g. int, short, while) in blue. Pause for every 23 lines (one page). Wait for the user to press <Space> to display the next page. If the user press <b>, then back to the previous page. If the user press <q>, then quit the program.

50 HW: Matching a string in files
Create an executable file “find.exe” so that running the command “find string file1 file2 file3 …” will search the named files and print out lines containing the string. Show the matched string with a highlighted color to emphasize it. For example: “find el message.txt book.txt” message.txt:Well, you are welcome. book.txt:Hello Hello

51 春怨 ~ 王逢原 三月殘花落更開, 小簷日日燕飛來。 子規夜半猶啼血, 不信東風喚不回。
春怨 ~ 王逢原 三月殘花落更開, 小簷日日燕飛來。 子規夜半猶啼血, 不信東風喚不回。 詩題「春怨」,意即怨春歸去。暮春時節,桃花、李花、海棠都已謝盡,春天花季中最後的荼蘼花又接著綻放,一春花事就要終了,春燕也留連不捨,仍天天飛來。杜鵑鳥從白天啼到半夜,都已叫出血來,非要喚回春天不可。   傳說蜀王 杜宇(望帝),被迫讓位後歸隱山林,死後魂魄化為杜鵑鳥,日夜悲啼,叫到口吐鮮血,哀鳴而亡。白居易的琵琶行中也有「杜鵑啼血猿哀鳴」的詩句。在這裡,詩人王逢原把杜鵑啼血的悲傷,想像成不信春光喚不回的執著。但是該走的總是要走,雖然不信而春去依舊,又何苦啼血至此呢!   王逢原 5歲時父母相繼去世,唯一的姊姊又已出嫁,他隨著叔祖父王乙到廣陵居住。17歲時離開叔祖父,接回寡居的姊姊和外甥,在天長、高郵等地教書來養活一家三口,從此開始他貧苦流浪的日子。   宋仁宗至和元年(1054),王安石應召進京,路過高郵,王逢原託人送了一首詩給王安石請他接見。王安石稱讚他是可以擔當重任而有功於天下的人才,從此王逢原與 大他11歲的王安石書信往返,成為莫逆之交。可惜王逢原才高命短,沒幾年年就在貧病交加中過世了, 年僅28歲。 這首詩每個人欣賞的角度不同。有人著眼於杜鵑啼出血來也喚不回東風,象徵過於執著只會徒增傷感;有人欣賞它的平仄諧韻。希望你也可以從中,找到你喜愛的部份。

52 Chapter 4 Arrays, Strings, and Pointers

53 Most Value Player Given the names of 10 players:
char player[10][20] = {"Alice", "Bob", "Charlie", "Dennis", "Emily", "Francis", "Grace", "Horace", "Indiana", "Julia" }; Also given the points of these 10 players: unsigned short Points[N] = { 46, 17, 87 , 75, 79, 70, 30, 99, 35, 26 }; Can you find the player with the highest points?

54 MVP #include <iostream> using std::cout; int main() { const unsigned short N = 10; char player[N][20] = { "Alice", "Bob", "Charlie", "Dennis", "Emily", "Francis", "Grace", "Horace", "Indiana", "Julia" }; unsigned short Points[N] = { 46, 17, 87 , 75, 79, 70, 30, 99, 35, 26 }; unsigned short max = Points[0]; int i, p; for (i=1; i<10; i++) if (max < Points[i]) max = Points[i]; p = i; } cout << "No." << p << " (" << player[p] << ") " << "got " << Points[p] << " Points.\n"; return 0;

55 3 Most Value Players How do you find the 2 players with highest points? Find the top 1 in the first pass. And find the second one in the second pass. How do you find the 3 players with highest points? Find the second one in the second pass. Find the third one in the third pass.

56 You have troubles if points[] has duplicate values.
mvp1.cpp #include <iostream> using std::cout; int main() { const unsigned short N = 10; char player[N][20] = { "Alice", "Bob", "Charlie", "Dennis", "Emily", "Francis", "Grace", "Horace", "Indiana", "Julia" }; unsigned short points[N] = { 46, 17, 87 , 75, 79, 70, 30, 99, 35, 26 }; unsigned short max = points[0]; unsigned short max2 = 0; int i, p, p2; for (i=1; i<10; i++) if (max < points[i]) max = points[i]; p = i; } for (i=0; i<10; i++) if (points[i] != max && max2 < points[i]) max2 = points[i]; p2 = i; cout << "No." << p << " (" << player[p] << ") " << "got " << points[p] << " points.\n"; cout << "No." << p2 << " (" << player[p2] << ") " << "got " << points[p2] << " points.\n"; return 0; You have troubles if points[] has duplicate values.

57 Sorting In computer science, “sorting” is a common process to arrange items in a pre-defined order (usually ascending or descending). 46, 17, 87 , 75, 79, 70, 30, 99, 35, 26 ascending: 17, 26, 30, 35, 46, 70, 75, 79, 87, 99 descending: 99, 87, 79, 75, 70, 46, 35, 30, 26, 17 After a sequence is sorted, it is quite easy for us to find the highest or lowest N items.

58 Sorting Input a sequence of numbers Rearrange them in ascending order.
For example: Input: 1, 3, 5, 7, 2, 4, 6 Output: 1, 2, 3, 4, 5, 6, 7

59 Exchange Sort 9 5 7 2 Compare 9 to 5; 9 is greater than 5 so swap them

60 Exchange Sort 5 9 7 2 Compare 5 to 7; 5 is smaller than 7 so leave them alone

61 Exchange Sort 9 7 5 2 Compare 5 to 2, 5 is greater than 2 so swap them

62 Exchange Sort 2 9 7 5 Notice that 2 is where it belongs
Start back at the second element...

63 Exchange Sort 2 9 7 5 Compare 9 to 7; 9 is greater than 7 so swap them

64 Exchange Sort 2 7 9 5 Compare 7 to 5; 7 is greater than 5 so swap them

65 Exchange Sort 2 5 9 7 Notice that 5 is now in the right place
Start back at the third element

66 Exchange Sort 2 5 9 7 Compare 9 to 7; 9 is greater than 7 so swap them

67 Exchange Sort 2 5 7 9 End of n-1 pass, sorting is done.

68 Sample Code (exchange_sort.cpp)
const int MAX = 4; int data[MAX] = { 9, 5, 7, 2}; int i, j, temp; cout << "Before soring:\t"; for (i=0; i<MAX; i++) cout << data[i] << '\t'; for (j=0; j<=MAX-2; j++) { cout << endl << "Round " << j+1 << ":\t"; for (i=j+1; i<=MAX-1; i++) if (data[j] > data[i]) temp = data[j]; data[j]=data[i]; data[i]=temp; }

69 Exercise: Exchange Sort
Modify exchange_sort.cpp so that the items are sorted in descending order.

70 Apply Sorting to Find 3 MVPs
Given an array of points { 46, 17, 87 , 75, 79, 70, 30, 99, 35, 26 } After descending sort, it becomes { 99, 87, 79, 75, 70, 46, 35, 30, 26, 17 } What do we know the players’ names corresponding to these 3 points? Solution 1: Exchange the items in player[] when we exchange items in points[].

71 mvp2.cpp for (j=0; j<=MAX-2; j++) { cout << "\nRound " << j+1 << ":\n"; for (i=j+1; i<=MAX-1; i++) if (points[j] < points[i]) temp = points[j]; points[j]=points[i]; points[i]=temp; strcpy(temp_name, player[j]); strcpy(player[j], player[i]); strcpy(player[i], temp_name); } for (i=0; i<MAX; i++) cout << points[i] << '\t'; cout << '\n'; cout << player[i] << '\t';

72 Running mvp2.cpp

73 This Would Be Quite Complex
Consider we also have arrays to store the heights and weights, and maybe birthdays of these players. This implies that you have lots of data to exchange in a single comparison!

74 Solution 2: Using Pointers
We can have an array, in which each element is a pointer, pointing to a corresponding player. Player Alice Bob Charlie Dennis points 46 17 87 75 Order

75 Compare the two points Compare 46 and is greater than 17, so leave them alone. Player Alice Bob Charlie Dennis Points 46 17 87 75 Order

76 Exchange the pointers Compare 46 and is less than 87, so swap the two corresponding pointers. Player Alice Bob Charlie Dennis points 46 17 87 75 Order

77 Compare two points Player Alice Bob Charlie Dennis points 46 17 87 75
Order

78 Compare two points Compare 87 and is greater than 75, so leave them alone. Player Alice Bob Charlie Dennis points 46 17 87 75 Order

79 Exchange the pointers Compare 17 and is less than 46, so swap the two pointers. Player Alice Bob Charlie Dennis points 46 17 87 75 Order

80 Exchange the pointers Player Alice Bob Charlie Dennis points 46 17 87
75 Order

81 Exchange the pointers Compare 46 and is less than 75, so swap the two pointers. Player Alice Bob Charlie Dennis points 46 17 87 75 Order

82 Exchange the pointers Player Alice Bob Charlie Dennis points 46 17 87
75 Order

83 Exchange the pointers Compare 17 and is less than 46, so swap the two pointers. Player Alice Bob Charlie Dennis points 46 17 87 75 Order

84 Sorted Now the array Order[] points to items in points[] with descending order! Player Alice Bob Charlie Dennis points 46 17 87 75 Order

85 mvp3.cpp const unsigned short MAX = 10; char player[MAX][20] = { "Alice", "Bob", "Charlie", "Dennis", "Emily", "Francis", "Grace", "Horace", "Indiana", "Julia" }; unsigned short points[MAX] = { 46, 17, 87 , 75, 79, 70, 30, 99, 35, 26 }; unsigned short Order[MAX] = { 0 }; unsigned short temp; int i, j, p; for (i=0; i<MAX; i++) Order[i] = i; for (j=0; j<=MAX-2; j++) { for (i=j+1; i<=MAX-1; i++) if (points[ Order[j] ] < points[ Order[i] ]) temp = Order[j]; Order[j]=Order[i]; Order[i]=temp; } cout << points[ Order[i] ] << '\t'; cout << '\n'; cout << player[ Order[i] ] << '\t'; Horace Charlie Emily Dennis Francis Alice Indiana Grace Julia Bob

86 From Arrays to Pointers
In C language, with an array, you can refer to different elements with a single array name, plus an index. a1, a2, a3 a[1], a[2], a[3] Furthermore, C language allows you to access arbitrary data (not only elements in an array) with a pointer.

87 Indirect Data Access with Pointers (P.146)
Each memory location which you use to store a data value has an address. A pointer is a variable that stores an address of another variable (of a particular type). e.g., the variable pnumber is a pointer It contains the address of a variable of type int We say pnumber is of type ‘pointer to int’. . 3000 3004 3008 300C 1 2 3 4 a=1; b=2; c=3; d=4; pnumber=0x3000

88 Declaring Pointers To declare a pointer of type int, you may use either of the following statements: int* pnumber; int *pnumber; You can mix declarations of ordinary variables and pointers in the same statement: int* pnumber, number = 99; int *pnumber, number = 99; Note that number is of type int instead of pointer to int. It is a common convention in C++ to use variable names beginning with p to denote pointers.

89 The Address-Of Operator
How do you obtain the address of a variable? pnumber = &number; Store address of number in pnumber (P.147)

90 Show the memory address
#include <iostream> using std::cout; using std::endl; using std::hex; int main() { int a=1, b=2; cout << hex << &a << hex << &b << endl; printf("%x %x\n", &a, &b); printf("%d %d\n", &a, &b); return 0; } 0x7fffffffdafc0x7fffffffdaf8 ffffdafc ffffdaf8

91 Initializing Pointers
int number(0); int* pnumber(&number); int* pnumber = NULL; int* pnumber = 0; No object can be allocated the address 0, so address 0 indicates that the pointer has no target. Visual C++ suggests you to use nullptr, but this is not supported by clang++, so I don’t recommend. You could test the pointer if (pnumber == NULL) cout << endl << "pnumber is null."; if (!pnumber) cout << endl << "pnumber is null.";

92 The Indirection Operator
Use the indirection operator *, with a pointer to access the contents of the variable that it points to. Also called the “de-reference operator” Ex4_06.cpp on P.149 *pnumber += 11; number1 += 11; number1 = number1 + 11;

93 Why Use Pointers? (P.148) Use pointer notation to operate on data stored in an array Chapter 4 Enable access within a function to arrays, that are defined outside the function Chapter 5 Refer to different functions with a pointer Chapter 6 Allocate space for variables dynamically. Chapter 7

94 Pointers to char (P.150) This looks similar to a char array.
char* proverb = "A stitch in time saves nine."; This looks similar to a char array. char proverb[] = "A stitch in time saves nine."; It creates a string literal (an array of type const char) with the character string appearing between the quotes, and terminated with \0 It also stores the address of the literal in the pointer proverb. Compare Ex4_05 on P.144 with Ex4_07 on P.151 cout will regard ‘pointer to char’ as a string

95 Arrays of Pointers char* pstr[] = { "Rober Redford",
"Hopalong Cassidy", "Lassie", "Slim Pickens", "Boris Karloff", "Oliver Hardy" };

96 Using pointers may eliminate the waste of memory that occurred with the array version.
In Ex4_04, the char array occupies 80 * 6 = 480 bytes. In Ex4_06, the array occupies 103 bytes. The longest string “Hopalong Cassidy” actually occupies 17 bytes, declaring a string array will at least occupy 17*6 = 102 bytes. (P.154)

97 The sizeof Operator (1) One problem of Ex4_07 (P.151) is that, the number of strings (6) is “hardwired” in the code. If you add a string to the list, you have to modify the code to and change it to be 7. Can we make the program automatically adapt to however many strings there are?

98 The sizeof Operator (2) The sizeof operator gives the number of bytes occupied by its operand It produces an integer value of type size_t. size_t is a type defined by the standard library and is usually the same as unsigned int. Consider Ex4_07 cout << sizeof dice; This statement outputs the value 4, because int occupies 4 bytes. cout << sizeof(int); You may also apply the sizeof operator to a type name rather than a variable cout << sizeof pstr; This statement outpus the value 24, the size of the whole pointer array. Ex4_08.cpp (P.152) can automatically adapt to an arbitrary number of string values.

99 Pointers and Arrays Array names can behave like pointers. If we have
If you use the name of a one-dimensional array by itself, it is automatically converted to a pointer to the first element of the array If we have double* pdata; double data[5]; you can write this assignment pdata = data; Initialize pointer with the array address pdata = &data[1]; pdata contains the address of the second element

100 Pointer Arithmetic You can perform addition and subtraction with pointers. Suppose pdata = &data[2]; The expression pdata+1 would refer to the address of data[3]; pdata += 1; Increment pdata to the next element The value of pdata will actually increase by sizeof(double) instead of only 1. pdata++;

101 De-reference a Pointer with Arithmetic
Assume pdata is pointing to data[2], *(pdata + 1) = *(pdata + 2); is equivalent to data[3] = data[4]; Tips: *(data + i) == data[i] (P.157)

102 Exercises Read Ex4_09.cpp (P.158 Calculating primes) and try to draw the flowchart manually. Re-write it by accessing the elements by array indices instead of pointers. Modify Ex4_08.cpp (P.152) to test the sizeof() function. Try to measure the size of a string array, an integer array, and so on. To initialize the variable dice, the textbook use “int dice ();”, but my recommendation is int dice = 0;

103 Dynamic Memory Allocation (P.163)
Postpone until Chapter 7 Sometimes depending on the input data, you may allocate different amount of space for storing different types of variables at execution time int n = 0; cout << "Input the size of the vector - "; cin >> n; int vector[n]; error C2057: expected constant expression

104 Free Store (Heap) To hold a string entered by the user, there is no way you can know in advance how large this string could be. Free Store - When your program is executed, there is unused memory in your computer. You can dynamically allocate space within the free store for a new variable.

105 The new Operator Request memory for a double variable, and return the address of the space double* pvalue = NULL; pvalue = new double; Initialize a variable created by new pvalue = new double(9999.0); Use this pointer to reference the variable (indirection operator) *pvalue = ;

106 The delete Operator When you no longer need the (dynamically allocated) variable, you can free up the memory space. delete pvalue; Release memory pointed to by pvalue pvalue = 0; Reset the pointer to 0 After you release the space, the memory can be used to store a different variable later.

107 Allocating Memory Dynamically for Arrays
Allocate a string of twenty characters char* pstr; pstr = new char[20]; delete [] pstr; Note the use of square brackets to indicate that you are deleting an array. pstr = 0; Set pointer to null

108 Dynamic Allocation of Multidimensional Arrays
Allocate memory for a 3x4 array double (*pbeans)[4]; pbeans = new double [3][4]; Allocate memory for a 5x10x10 array double (*pBigArray)[10][10]; pBigArray = new double [5][10][10]; You always use only one pair of square brackets following the delete operator, regardless of the dimensionality of the array. delete [] pBigArray;

109 3/25 春季健行


Download ppt "送孟浩然之廣陵 ~ 李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧山盡, 唯見長江天際流。."

Similar presentations


Ads by Google