1 / 123

Chapter 5 Array, Pointers and Strings

Chapter 5 Array, Pointers and Strings. By C. Shing ITEC Dept Radford University. Objectives. Understand how to use arrays (one and multiple dimensions) Understand how to use pointers Understand the relationship between pointers and arrays Understand how to call function using

rocio
Télécharger la présentation

Chapter 5 Array, Pointers 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. Chapter 5 Array, Pointers and Strings By C. Shing ITEC Dept Radford University

  2. Objectives • Understand how to use arrays (one and multiple dimensions) • Understand how to use pointers • Understand the relationship between pointers and arrays • Understand how to call function using pass-by-reference and pass-by-value • Understand how to create dynamic memory

  3. Objectives (Cont.) • Understand how to pass function as argument • Understand how to use strings • Understand the relationship between pointers and strings • Understand array of pointers • Understand how to use command line arguments • Understand how to use Library function: scanf

  4. Array • A contiguous memory with the same data type • Declared as • 1-dimension type array_name [array_size]; • 2-dimension type array_name [row_size][coulmn_size]; …

  5. Array (Cont.) • Has index (or indices) starting from 0 to access each memory • 1-dimension: specify the content at index array_name[index] Example: type array_name [array_size]; declare memory: array_name[0], array_name[1], …, array_name[array_size-1] • 2-dimension: specify the content at row_index and column_index array_name[row_index][column_index]

  6. Array (Cont.) • Programmer must make sure that indices are not out of bound. Otherwise, buffer overflow security problem will occur.

  7. Array (Cont.) • Initialization: • row-wise (starts fill in 1st row first) • Fill in 0 if not enough initial integer values specified • Form: • 1-dimension: type array_name[array_size] = {initial values}; • 2-dimension: type array_name[row_size][column_size] = {{row 0 initial values}, …, {row row_size-1 initial values}}

  8. Array (Cont.) • Initialization: (Cont.) • Example: • 1-dimension: int a [4] = {4,3,2,1}; or int a[]={4,3,2,1}; Then a[0]=4, a[1]=3, a[2]=2, a[3]=1 • 2-dimension: int a[3][4] = {{10,11,12,13}, {20,21,22,23}, {30,31,32,33}} or int a[][]= {{10,11,12,13}, {20,21,22,23}, {30,31,32,33}} or int a[][4]= {10,11,12,13, 20,21,22,23, 30,31,32,33} Then a[0][0]=10, a[0][1]=11, a[0][2]=12, a[0][3]=13, …, , a[2][0]=30, a[2][1]=31, a[2][2]=32, a[2][3]=33

  9. Array (Cont.) • Initialization: (Cont.) • Example: (Cont.) • 1-dimension: int a [4] = {4,3}; Then a[0]=4, a[1]=3, a[2]=0, a[3]=0 • 2-dimension: int a[3][4] = {{10}, {20,21,22}, {30,31}} Then a[0][0]=10, a[0][1]=a[0][2]=a[0][3]=0, a[2][0]=30, a[2][1]=31, a[2][2]=a[2][3]=0

  10. Array (Cont.) • Initialization: (Cont.) • Example: Initialize the whole array • 1-dimension: int a [4] = {0}; Then a[0]=0, a[1]=0, a[2]=0, a[3]=0 • 2-dimension: int a[3][4] ={0} Then a[0][0]=a[0][1]=a[0][2]=a[0][3]=…= a[2][0]= a[2][1]=a[2][2]=a[2][3]=0

  11. Pointers • Store address using a word • More efficient than using index • Declare as: type *pointer_variable; This request a word size pointer_variable that stores an address of the type Note: do not use pointer to a register type variable • Use in a statement: (Referencing/Addressing operator &) pointer_variable = & type_variable; The pointer_variable stores the address of the type_variable Note: do not use & expression

  12. Dereferencing Operator * • Find the content that pointed by an address • Use in a statement: variable = * pointer_variable; Example: int i , *p; i= 10; p= &i; j= *p; Then j also contains 10. (Note: & and * cancel each other) • Example

  13. Top-Down Design Example - Use Pointer • Example: write a program to convert a series of Fahrenheit degrees into Celsius degree (use sentinel -1 to stop) The Output will look like Fahrenheit Celsius _________ ______ 212.00 100.00 32.00 0.00

  14. Top-Down Design Example - Use Pointer • Functions: 1st level: main(void) 2nd level: PrintHeading: this function prints header and __ in screen input: nothing output: nothing GetInput: this function reads data from keyboard and stores fahrenheit degree input: fahrenheit address (double*)- due to pass by value output: nothing ProcessData: this function converts the fahrenheit to celsius degree input : fahrenheit (double) and celsius address (double *) from main output : nothing OutputResult: this function prints out fahrenheit and celsius degrees in screen input: fahrenheit (double), celsius (double) from main output : nothing

  15. Top-Down Design Example - Use Pointer • program data Top-Down Design Example - Use Array • Program (sentinel: -1) data

  16. Array and Pointer Relation • Array name stores address of the array • 1-dim: type array_name [array_size]; The base address is &array_name[0] The array_name stores &array_name[0] The (array_name+i) stores &array_name[i] Example: int a[N], *p; p = a; // p = &a[0] p= a+i; // p=&a[i] Note: if the address of the array a is 1000, then p contains the address= 1000+ i*sizeof(int), which is not 1000+i • Example

  17. Array and Pointer Relation (Cont.) • Do not attempt to change the address of the array Example: int a[100], *p; & 100 is not allowed &a is not allowed ++a is not allowed a = (int *) 100 is not allowed p= (int *) 100 is allowed

  18. Array and Pointer Relation (cont.) • Array name stores address of the array (Cont.) • 2-dim: type array_name [row_size][column_size]; The base address is &array_name[0][0] The array_name stores &array_name[0]: beginning address of 1st row (different from &array_name[0][0]) The (array_name+i) stores &array_name[i]

  19. Array and Pointer Relation (cont.) Example: int a[M][N], *p; p = a; // p = &a[0], where a[0] is an array of N elements // *p is the array a[0], which contains N elements p= a+i; // p=&a[i] Class Example

  20. Array and Pointer Relation (cont.) • Array name stores address of the array (Cont.) • 2-dim: Question: int a[M][N], *p; Can you use pointer p (where p=&a[0][0]) to find a[i][j]?

  21. Array and Pointer Relation (cont.) • Array name stores address of the array (Cont.) • 2-dim: (Cont.) int a[M][N], *p; p=&a[0][0]; Answer: a[i][j]=*(p+i*N+j)

  22. Array and Pointer Relation (cont.) • Array name stores address of the array (Cont.) • 2-dim: Question: int a[M][N], *p; p=a; Can you use pointer p to find a[i][j]?

  23. Array and Pointer Relation (cont.) Idea: • Find address of 1-dim array a[i] by (a+i) • Find the 1 dim array a[i] by *(a+i). Then if you use index now, the cell a[i][j] content is either (*(a+i))[j] or • Find the address of the cell j of a[i] by *(a+i)+j • The cell a[i][j] content is *(*(a+i)+j) Note: when you cast (int *) on a, then it specifies the base address &a[0][0] See Example.

  24. Array and Pointer Relation (cont.) • Array name stores address of the array (Cont.) • 2-dim: (Cont.) int a[M][N], *p; p=a; Answer: • a[i][j]= (*(p+i))[j] or • a[i][j]= *(*(p+i)+j) Is the following correct? a[i][j]= *(p+i+j) Why?

  25. Array and Pointer Relation (cont.) See Example1 or Example 2 Summary Example

  26. Operators Priority

  27. Operators Priority (Cont.)

  28. Passing Array Element to Functions • Pass-by-value: pass a copy of only some or an array element • The array element will not be changed after function call Syntax: functionname(a[n]); • Example

  29. Passing Entire Array to Functions • Pass-by-reference: pass the address of an entire array • Only a word size is passed, very efficient • ANSI C uses pass by reference for entire array only • The array content can be changed however the array address is not changed • ANSI C provides const type to prevent the whole array is accidentally changed Syntax: functionname(a); Example

  30. Passing Array Element to Functions- by Value • Example: 1-dim int a[100]; a[0]=0; byValue(a[0]); printf(“a[0]=%d”,a[0]); // a[0]=0 is printed void byValue(int b) { b=100; }

  31. Passing Array to Functions- by Reference • Example: 1-dim int a[100], i; for (i=0;i<100;++i) a[i]=i; byReference(a); for (i=0;i<100;++i) printf(“a[%d]=%d”,i,a[i]); // a[0]=100, a[1]=99, … are printed void byReference(int *a) // a is a pointer { int i; for (i=0;i<100;++i) a[i]=100-i; // use pointer[index] to specify the cell element }

  32. Use Array • Read in data to function inputData and returns count of number of data: array1.c syntax: count = functionname(…); • Read in data to function inputData and store count of number of data in a variable count: array3.c syntax: functionname(…, &count , …); Example: using 1-dim int array (read in character), data

  33. Use Array (Cont.) • Linear Search: array2.c, Data: array2_data.txt • Run: (Use a sentinel -1) a.out < array2_data.txt

  34. Class Example • Example. 2D array vendor Write a program to use the following input and produce the output. Input(keyboard): For each vendor, prompt for and enter the following data: (by storing them in a file and use redirect input from the file) Vendor Invoice Invoice Discount Number Number Amount Rate • 1239 2309.12 0.10 • 9823 670.00 0.09

  35. Class Example (Cont.) • Example. 2D array vendor (Cont.) Output(screen): For each vendor, print the following report: Author ACCOUNTS PAYABLE Invoice Number: XXXX Vendor Number: XXX Invoice Amount: $99999.99 Discount Amount: $ 999.99 Amount Due: $99999.99 Example

  36. Class Example (Cont.) • Example. 2D array vendor (Cont.) Example 1: program for input and output, data a.out < 2d.txt Example2 : 1 row data only • Example: 2D array input & output Hint to HW #2, test data

  37. Class Example (Cont.) • Example: (Cont.) The following segment has a run-time error on void input_data (double *vendor) : Why? #define MAXSIZE 50 void input_data (double *vendor); int main (void) { double vendor[MAXSIZE][4]; input_data (vendor); } void input_data (double *vendor) { int i, j; for (i=0;i<MAXSIZE;i++) for (j=0;j<4;j++) scanf(“%lf”, &vendor[i][j]); }

  38. Class Example (Cont.) • Example : (Cont.) Answer: The bug is at void input_data (double *vendor); And void input_data (double *vendor) { … scanf(“%lf”, &vendor[i][j]); }

  39. Class Example (Cont.) • Example : (Cont.) Answer: (Cont.) Reason: when you pass vendor into function input_data It is the address of the array: vendor[0] There is no such thing as vendor[i][j] used in scanf statement.

  40. Class Example (Cont.) • Example : (Cont.) Answer: (Cont.) Correction: #define MAXSIZE 50 void input_data (double vendor[][4]); int main (void) { double vendor[MAXSIZE][4]; input_data (vendor); } void input_data (double vendor[][4]) { int i, j; for (i=0;i<MAXSIZE;i++) for (j=0;j<4;j++) scanf(“%lf”, &vendor[i][j]); }

  41. Bubble Sort • Sort an array of int: a[0], …, a[count-1] • # of passes: count -1 • Program, Data • Another way of using array address: also use const on formal parameters to prevent accidental parameter values changed

  42. Passing Array to Functions- by Reference (Cont.) • Example: 1-dim int a[100], i; void bubble_sort (int a[], int n) { int i,j; for (i=0;i<n-1;++i) for (j=n-1;j>i;--j) … swap (a+j-1, a+j); // swap a[j-1] and a[j] }

  43. Passing Array to Functions- by Reference (Cont.) • Example: (Another version of bubble sort) • 1-dim int a[100], i; void bubble_sort (int a[], int n) { int i,j; for (i=0;i<n-1;++i) for (j=0;j<n-i-1;++j) if (a[j]>a[j+1]) swap (a+j, a+j+1); // swap a[j] and a[j+1] }

  44. Passing Array to Functions- by Reference (Cont.) • Example: 1-dim (Cont.) void swap (int *const a, int * const b) // a and b are pointers { int tmp; tmp=*a; *a=*b; *b=tmp; }

  45. Passing 2D Array to Functions- by Reference • Example: 2-dim int a[10][100], i, j; for (i=0;i<10;++i) for (j=0;j<100,++j) a[i][j]=i*j; byRef (a); for (i=0;i<10;++i) for (j=0;j<100,++j) printf(“a[%d][%d]=%d”,i,j,a[i][j]); // a[0][0]=100, a[0][1]=99, … are printed void byRef (int a[][100]) { int i, j; for (i=0;i<10;++i) for (j=0;j<100,++j) a[i][j]=100-i-j; }

  46. Use Pointers only instead of indexing • Example Remember you must define spaces for array before using pointers. Otherwise, runtime error informs you due to no spaces can be assigned beyond the pointer that you declared.

  47. Strings • Array of characters end with ‘\0’ • String name is a pointer to the base address (i.e. the address of the 1st character) • Initialize by char *s=“string constant”; // initialization specifies the length of s = 16 or char s[] =“string constant”; or char s[] ={‘s’,’t’,…, ‘n’, ‘t’,’\0’};

  48. String and Pointer Relation • Similar to the array and pointer relation Example:char *p=“constant”; printf(“%s\n”, p+2); // nstant printed printf(“%c\n”, p[5]); // a printed printf(“%c\n”, *(p+4)); // t printed

  49. String Functions • Use string function to work on strings • String functions are defined in string.h • String functions (not secure- buffer overflow attack): strings s and t • strcat (char *s, const char *t): s=s concatenate t • strcpy (char *s, const char *t): s=copy of t until ‘\0’ of t is reached • strcmp (char *s, const char *t): <0 if s<t =0 if s=t >0 if s>t • strlen (const char *s): return string length before ‘\0’, an unsigned integer or long int (type size_t) • strerror (int errornum): returns pointer to system dependent error message

  50. String Functions (Cont.) • String functions are defined in string.h • String functions (More secure): strings s and t • strncat (char *s, const char *t, size_t n): s=s concatenate at most n characters of t • strncpy (char *s, const char *t, size_t n): s=copy of at most n characters of t • strncmp (char *s, const char *t, size_t n): compare up to n characters of s with t <0 if s<t =0 if s=t >0 if s>t

More Related