Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures.

Similar presentations


Presentation on theme: "1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures."— Presentation transcript:

1 1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series

2 2 An unsolved question … What if I want to pass many parameters to a function, such as a set of numbers, or an array? What if I expect many outputs from a function, such as a set of numbers? Specifically, –How to compare two strings? –How to copy one string to another one? –How to change all the letters in a string to capital letters?

3 3 What will we learn today? A brief review of what we’ve learnt More on Call-by-Value and Call-by-Ref. Passing arrays to functions Array of pointers

4 4 A Brief Review Concepts: –Variable, type, value, pointer, reference When I declare an array, i.e., int a[3], what will happen in the memory? OS reserve a block of memory for a[3] compiler will not check the range of the array!!!  a[5] will not produce any syntax error a is a pointer, pointing to &(a[0]) int b = 2; int &c = b; // just an alias a[0] a[1] a[2] a 00600001 b (c) &b &c

5 5 Calling Functions by Reference Call by reference –Pass address of argument –Allows you to change the original data in memory Pass a reference and pass a pointer void fun(int *); void main() { int n = 2; fun(&n); } void fun( int *ptr ) { (*ptr) *= 2; } void fun(int &); void main() { int n = 2; int &r_n = n; fun(r_n); // fun(n); // same } void fun( int &x ) { x *= 2; }

6 6 Question? Yes, I know how to pass a piece of data to a function. But if I have a set of data, (e.g., the grades of 100 students), –Q1: if my function is to calculate the average, how can I pass such a set of data to the function? –Q2: If my function is to adjust their grades, e.g., sqrt(x i )*10, how can I do that?

7 7 One Solution  A naïve solution –Call-by-value: you copy the whole array, and pass all of them through the function parameters int Avg(int a1, int a2, int a3, int a4, int a5, ……………… ); Why this solution is not sound? 00601000 stack seg. a[0] a[1] a[2] a[99] Solution I s. p. a[1] 00300001 data seg. a[0] a[99] a

8 8 A Better Solution! Solution: –Store all the data in an array –Then pass the address and the length of this array How does it work? Guess: what would be the function prototype look like? –How do I know where the array is located? –How do I know the size of the array? –How to tell my function what I pass is an array? a[1] 00300001 data seg. a[0] a[99] a 00601000 stack seg. 00300001 100 Solution II s. p.

9 9 Passing Arrays to Functions Function prototype: void modifyArray( int b[], int arraySize ); –Parameter names optional in prototype int b[] could be simply int [] int arraysize could be simply int void modifyArray( int [], int );

10 10 Example int Avg(int a[], int size); void Promote(int a[], int size); void main() { int score[10] = {80,90,70,75,95,100,85,90,70,95}; int mean; mean = Avg(score, 10); if(mean<80){ Promote(score, 10); } else{ cout << “Good!”; } #include int Avg(int a[], int size) { assert(size>0); int tmp = 0; for(int k=0;k<size;k++) tmp += a[k]; return tmp/size; } void Promote(int a[], int size) { for(int k=0; k<size; k++) a[k] = 10*sqrt(a[k]); }

11 11 A Trick! As we know, a rule of thumb is that –the name of an array is the address of the 1 st element, –or a pointer that points to the 1 st element So, we can roughly say –“an array and a pointer are equivalent”. Thus, we can use pointers for indexing –It is flexible and convenient. int a[10] = {1,2,3,4,5,6,7,8,9,10}; int *p = &(a[5]); p[0] = ? p[4] = ? p[5] =? –But, it is dangerous, as well.  C/C++ will never do the range check for you!

12 12 Passing pointers to functions int Avg(int *pa, int n); void Promote(int *pa, int n); void main() { int score[10] = {80,90,70,75,95,100,85,90,70,95}; int mean; mean = Avg(score, 10); if(mean<80){ Promote(score, 10); } else{ cout << “Good!”; } #include int Avg(int *pa, int n) { assert(n>0); int tmp = 0; for(int k=0;k<n;k++) tmp += pa[k]; return tmp/size; } void Promote(int *pa, int n) { for(int k=0; k<n; k++) pa[k] = 10*sqrt(pa[k]); }

13 13 To ensure yourself! The basic idea of CBR is to let you pass an address to functions, such that –You can pass a set of data to functions –You let the function modify the original data To use CBR, your function will –Either make modification of the originals –Or doesn’t You, as a programmer, must be sure of that. –If you don’t allow the function change the original data, then a good practice is to use a specific modifier “ const ” to indicate –If your function does modify the data which is not what you want, then the Compiler will let you know, and reduce the risk.

14 14 Using const int Avg(const int *pa, int n); void Promote(int *pa, int n); void main() { int score[10] = {80,90,70,75,95,100,85,90,70,95}; int mean; mean = Avg(score, 10); if(mean<80){ Promote(score, 10); } else{ cout << “Good!”; } #include int Avg(const int *pa, int n) { assert(n>0); int tmp = 0; for(int k=0;k<n;k++) tmp += pa[k]; return tmp/size; } void Promote(int *pa, int n) { for(int k=0; k<n; k++) pa[k] = 10*sqrt(pa[k]); }

15 15 Wanna Compare two strings? bool CmpStr(const char *str1, const char *str2) { boolres = true; int index = 0; do{ if(str1[index] != str2[index]){ res = false; break; } index ++; } while(str1[index] != 0) return res; }

16 16 strcmp() C/C++ string library ( prototypes defined in string.h) int strcmp(const char *str1, const char *str2); Return value >0 if str1>str2 =0if str1==str2 <0 if str1<str2 E.g. “abc” < “bbc” “abc” < “acd” “abc” < “abd”

17 17 Wanna Copy a string? void CpyStr(char *to, const char *from) { int index = 0; while(from[index]!=0){ to[index] = from[index]; index ++; } to[index] = ‘\0’; }

18 18 Alert! When copying a string, you need to “reserve” enough space to hold the new string! //Will it work? void main() { char str1[] = “How are you!”; char *str2; CpyStr(str2, str1); CpyStr(str2, “fine”); } // will it work? void main() { char str1[] = “How are you!”; char str2[6]; CpyStr(str2, str1); CpyStr(str2, “fine”); }

19 19 Strcpy() C/C++ string library defines strcpy() char *strcpy( char *to, const char *from ); Return: the destination string. No return value is reserved to indicate an error. void main() { char string[80]; if ( strcpy( string, "Hello world!" )) cout << string << endl; else cout << “copying failed! << endl; }

20 20 Arrays of Pointers Arrays can contain pointers –Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" }; –Each element of suit is a pointer to a char * (a string) –The strings are not in the array, only pointers to the strings are in the array –suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’


Download ppt "1 Array, Pointer and Reference ( III ) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures."

Similar presentations


Ads by Google