CPP 3
CPP 3
Use of array in C++, multidimensional array, array argument passing Pointers Relation between pointer and array String, string processing functions
Arrays
Declaration of an array int c[12]; or const int max = 12; int c[max]; References to an array c[ ] c[0], c[1], , c[max-1]
Array Initialization
int n[5] = {1, 2, 3, 4, 5}; or int n[ ] = {1, ,2, 3, 4, 5}; n[0], n[1], , n[4] are valid references
C.f. Fig. 4.3
Passing Array
Passing an array name is equivalent to passing the address of the array int a[5]; // declare array func(a); // use function void func(int a[ ]) // define function { C.f Fig. 4.14 }
Multiple-Subscripted Arrays
int a[2][5]; A 2 by 5 array. Initialization int a[2][5] = { {0,1,2,3,4}, {0,2,4,6,8} }; Row major convention in C/C++
Pointers
Pointer value holds the address of a variable. Pointers are also typed, i.e, pointer to int is considered different from pointer to double. E.g., int *p; double *fpt;
p = &c; p = a; p = &a[0];
Dereferencing Operator *
int *p, c;
c = 1; p = &c; j = *p;
// let p point to c
// j gets 1,
a + b + c means (a+b) + c
Precedence
a + b*c means a + (b*c)
See Appendix A, page 1214 for the complete "Operator Precedence Chart".
Answer
b += (x = ((y - (k*(a[ j ]))) && (3 | (u < (v--)))));
C.f. Fig.5.7
Multi-Dimensional Array
In the declaration int a[3][7]; we can view a as pointer to array of a[0], a[1], a[2], which themselves are pointers to int array a[i][j]. **a is the same as a[0][0].
Pointer of Pointers
a a[0] a[1] a[2][0] a[2][1] a[2]
a[1][0]
a[0][0]
a[1][1] ...
Arrays of Pointers
char *suit[4] = { "Hearts", "Diamonds", "Clubs", "Spade"};
suit[0][0] refers to 'H', suit[3][4] refers to 'e' in "Spade", suit[2][20] is an illegal access.
Function Pointer
void (*f)(int); f is a pointer to a function of the form void g(int). Function names are like address, e.g, f = g; (*f)(5); // call the function
String Initialization
char color[ ] = "blue"; char *colorPtr = "blue"; char color[ ] = {'b', 'l', 'u', 'e', '\0'};
What is the difference between the array color and the pointer colorPtr?
Read a String
char word[20]; cin >> word; // cause problem cin >> setw(20) >> word; // OK Read an entire line char sentence[80]; cin.getline(sentence, 80);
String Processing
Exercise 4.29
(The Sieve of Eratosthenes) A prime integer is any integer that is evenly divisible only by itself and 1. Use the sieve method to find prime.
Initialize a[1000] all to 1 (for true). Starting from 2, 3, , k, ..., set array indices which are all multiple of k to 0, print the nonzero indices.