Upload
rocio
View
67
Download
3
Embed Size (px)
DESCRIPTION
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 - PowerPoint PPT Presentation
Citation preview
Chapter 5 Array, Pointers and Strings
By C. Shing
ITEC Dept
Radford University
Slide 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
Slide 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
Slide 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];…
Slide 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_indexarray_name[row_index][column_index]
Slide 6
Array (Cont.) Programmer must make sure that
indices are not out of bound.
Otherwise, buffer overflow security problem
will occur.
Slide 7
Array (Cont.) Initialization:
row-wise (starts fill in 1st row first) Fill in 0/NULL if not enough initial integer (pointer)
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}}
Slide 8
Array (Cont.) Initialization: (Cont.)
Example: 1-dimension:
int a [4] = {4,3,2,1};orint 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}}orint a[][]= {{10,11,12,13}, {20,21,22,23}, {30,31,32,33}}orint 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
Slide 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
Slide 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
Slide 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 typeNote: 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
Slide 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
Slide 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.0032.00 0.00
Slide 14
Top-Down Design Example - Use Pointer
Functions:1st level: main(void)
2nd level: PrintHeading: this function prints header and __ in screen
input: nothingoutput: nothing
GetInput: this function reads data from keyboard and stores fahrenheit degreeinput: fahrenheit address (double*)- due to pass by valueoutput: nothing
ProcessData: this function converts the fahrenheit to celsius degreeinput : fahrenheit (double) and celsius address (double *) from
mainoutput : nothing
OutputResult: this function prints out fahrenheit and celsius degrees in screeninput: fahrenheit (double), celsius (double) from mainoutput : nothing
Slide 15
Top-Down Design Example - Use Pointer
program
data
Top-Down Design Example - Use Array Program (sentinel: -1)
data
Slide 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
Slide 17
Array and Pointer Relation (Cont.) Do not attempt to change the address of the arrayExample:
int a[100], *p;
& 100 is not allowed&a is not allowed++a is not alloweda = (int *) 100 is not allowed
p= (int *) 100 is allowed
Slide 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]
Slide 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
Slide 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 base address p=&a[0][0])
to find a[i][j]?
Slide 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]; [Note: (int *)a also gives bas address]
Answer:a[i][j]= *(p+i*N+j) or a[i][j]= *((int *)a+i*N+j)
Slide 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]?
Hint: a[i]=*(a+i)
Slide 23
Array and Pointer Relation (cont.)Idea:1. Find address of 1-dim array a[i] by (a+i)2. 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] or3. Find the address of the cell j of a[i] by *(a+i)+j4. 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.
Slide 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:1. a[i][j]= (*(p+i))[j] or2. a[i][j]= *(*(p+i)+j)Is the following correct?a[i][j]= *(p+i+j)Why?
Slide 25
Array and Pointer Relation (cont.)See Example1
or
Example 2
Summary Example
Slide 26
Operators Priority
Operator Same Priority Rule
(),postfix++/--,[],.,-> Left to right
Unary +/-, prefix++/--, !, ~,&, * Right to left
*, /, % Left to right
+, - Left to right
<<, >> Left to right
<, >, <=, >= Left to right
==, != Left to right
Slide 27
Operators Priority (Cont.)
Operator Same Priority Rule
&
^
|
&& Left to right
|| Left to right
?: Right to left
, Left to right
Slide 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
Slide 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
Slide 30
Passing Array Element to Functions- by Value
Example: 1-dimint 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; }
Slide 31
Passing Array to Functions- by Reference
Example: 1-dimint 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
} See byReference.c
Slide 32
Use Array1. Read in data to function inputData and returns count of number of data: array1.c
syntax: count = functionname(…);2. 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
Slide 33
Use Array (Cont.) Linear Search: array2.c, Data: array2_data.txt Run: (Use a sentinel -1)
a.out < array2_data.txt
Slide 34
Class Example Example. 2D array vendorWrite 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 DiscountNumber Number Amount Rate217 1239 2309.12 0.10349 9823 670.00 0.09
Slide 35
Class Example (Cont.) Example. 2D array vendor (Cont.)Output(screen): For each vendor, print the following report: Author ACCOUNTS PAYABLEInvoice Number: XXXXVendor Number: XXXInvoice Amount: $99999.99Discount Amount: $ 999.99Amount Due: $99999.99
Example
Slide 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
Slide 37
Class Example (Cont.) Example: (Cont.)
The following segment has a run-time error on void input_data (double *vendor) : Why?
#define MAXSIZE 50void 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]);
}
Slide 38
Class Example (Cont.) Example : (Cont.)
Answer:The bug is at void input_data (double *vendor);Andvoid input_data (double *vendor) {
…scanf(“%lf”, &vendor[i][j]);
}
Slide 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.
Slide 40
Class Example (Cont.) Example : (Cont.)
Answer: (Cont.)Correction:
#define MAXSIZE 50void 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]);
}
Slide 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
Slide 42
Passing Array to Functions- by Reference (Cont.)
Example: 1-dimint 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]
}
Slide 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]
}
Slide 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;}
Slide 45
Passing 2D Array to Functions- by Reference
Example: 2-dimint 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;
}
Slide 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.
Slide 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’};
Slide 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
Slide 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
Slide 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
Slide 51
String Functions (Cont.) Example:
char * strcpy (char *s, register const char *t)
{
register char *p=s;
while (*p++=*t++);
return s;
}
Slide 52
Keyboard Input Function – gets (Not Secure: buffer overflow problem)
Form: gets (string_variable);Read from keyboard into string_variable until end of line or end of file
Example:char s[80]; // remember s is address, do not use char *sgets (s); // sample data:a 100 -1.23 This is a sample data// s=“a 100 -1.23 This is a sample data”
Slide 53
A Safer Keyboard Input Function - getline
A non-standard function Form: ssize_t getline (char **lineptr, size_t *n, FILE *stream) Read from keyboard into a string lineptr at most n characters until end of line or end of file
Note: A standard function called fgets does a similar job. See sscanf slide (Slide 64) Example link.
Example:
Slide 54
Keyboard Output Function - puts Form: puts (string_variable);Print the content of the address of string_variable
Example:void output_string (const char *s) { // remember s is address
puts (s); // print out s:a 100 -1.23 This is a sample data
}
Slide 55
Keyboard Input Format Function - scanf Form: scanf(“format”, variable_address);
Format: similar to those used in printf, see Chapter 3 If use %s format, it reads all until it reaches the first white space
Example:char c;int i;double db;char s[80]; // remember s is addressscanf(“%c%d%lf%s”, &c, &i, &db, s); // sample data:a 100 -1.23 This is a sample data// c=‘a’, i=100, db=-1.23, s=“This”
Slide 56
Example - scanf Program: read characters into an arrays
(lname and fname) and convert them to strings Data
Slide 57
Keyboard Input Format Function – scanf (Cont.)
Form: scanf(“pure_format”, variable_address); (Cont.) Scan set:
%[range]Reads every character which belongs to range, stop at the character (not read in) which does not belong to the range
%[^range]Reads every character which does not belongs to range, stop at the character (not read in) which belongs to the range
%10dRead in 10 digit number %10cRead in 10 characters %*cSkip any number of characters
Example: Program, DataHint to Quiz #5, Hint Data
Slide 58
Keyboard Output Format Function - printf
Form: printf(“format”, variable_address); Format: %s, see those used in printf, see Chapter 2
Slide 59
Search Strings Find the index of the array if found. Return -1 if not found
Example: read the following data into array of strings (max 8 characters)- no duplication
Data:ABC 123PLO4ME123456AL-QADA2PLO4ME123V456
Slide 60
Search Strings (Cont.)int i;char plate[9];char license[1000][9];int frequency[1000]={0};int count=0, index;// count: # of different licenses in license array
for (i=0;gets(plate);i++){
index = search(license, plate, count);…
}
Slide 61
Search Strings (Cont.)
if (index == -1)
{
strcpy(license[count], plate);
…
}
else
{ …}
Slide 62
Search Strings (Cont.)int search (char license[][9], char *plate, int count){
int i;
for (i=0; i<count; i++){
if (strcmp (license[i],plate)== 0)return i; // found plate in license array
}
return -1; // not found}
Slide 63
Input and Output String Format Function – sscanf and sprintf
Form: sscanf (instring, “format”, variable_address); Similar to scanf, it inputs data from string
instead of keyboard Format: similar to those used in printf, see Chapter 4 If use %s format, it reads all until it reaches
the first white space Form: sprintf (outstring, “format”, variable);
Similar to printf, it outputs results to string instead of screen
More secure one:Form: snprintf (outstring, n, “format”, variable);
Slide 64
Input and Output String Format Function – sscanf and sprintf (Cont.)
Example:char c;int i;double db;char s[80], outstring[80],
*instring=“a 100 -1.23 This is a sample data”; sscanf(instring,“%c%d%lf%s”, &c, &i, &db, s); //Then c=‘a’, i=100, db=-1.23, s=“This”sprintf(outstring,“%c%d%lf%s”, c, i, db, s); // print to outstring: a 100 -1.23 This Orsnprintf(outstring,“%c%d%lf%s”,80, c, i, db, s); // print to outstring: a 100 -1.23 This
Example, Data
Slide 65
Class Example sscanf and gets:
Example
Hint to HW Substring of “string” from location 2 to 3 is “tr”
Slide 66
String Search Utilities Need to include <string.h>
char* strchr(const char *s, int c): return pointer to the found character c in s. Returns NULL
otherwiseExample: strchr(“This is a sunny day.”, ‘u’): returns s+11 size_t strcspn(const char *s, const char *range):
returns length of initial s that are not in the rangeExample: strcspn(“This is a sunny day.”, “abcd”): returns 8
Slide 67
String Search Utilities (Cont.) size_t strspn (const char *s, const char *range):
returns length of initial s that are in rangeExample: strspn(“This is a sunny day.”, “hist”):
returns 4 since space is not in “hist” char *strpbrk (const char *s, const char *range):
returns pointer of the 1st character of s found in range
Example: strpbrk(“This is a sunny day.”, “abcd”):
returns pointer of ‘a’
Slide 68
String Search Utilities (Cont.) char * strrchr (const char *s, int c):
returns pointer of the last found character c in sExample:
strrchr(“This is a sunny day.”, “s”): returns position of s in sunny
char *strstr (const char *s, const char *range): returns pointer of the 1st occurrence of range found in s
Example: strstr(“This is a sunny day.”, “is”):
returns pointer of “is” in “This”
Slide 69
String Search Utilities (Cont.) char * strtok (const char *s, const char *delimiter):
returns pointer of the token in s using the delimiterand save the position of the next token
Example: char s[]=“This is a sunny day.”;
char *token;
token=strtok(s, “ “);
do {
printf(“token=%s\n”, token);token=strtok(NULL, “ “); // must use this to get next token
} while (token != NULL);
The tokens printed are:Thisisasunnyday.
Slide 70
Other General String Utilities void *memcpy
(void * destination, const void *source, size_t n):copies n items of source to destination returns pointer to the result
Note: this function cannot overwrite the destination object
Example: char s[] = “This is a sunny day.”; char t[80];
memcpy(t,s, 21); returns pointer of t= “This is a sunny day.”
Slide 71
Other General String Utilities (Cont.) void *memmove
(void * destination, const void *source, size_t n):copies n items of source to destination returns pointer to the result
Note: this function can overwrite the destination object
Example: char s[] = “This is a sunny day.”;
memmove(s,&s[10], 3); returns “suns is a sunny day.”
Slide 72
Other General String Utilities (Cont.) void *memcmp
(const void * s, const void *t, size_t n):compares the 1st n elements of s and t and returns 0 if s=t, -1 if s<t, 1 if s>t
void *memchr (const void * s, int c, size_t n):returns pointer of the 1st found c in the 1st n elements of sExample: char s[] = “This is a sunny day.”;
memchr (s, ‘u’,16); returns pointer of “unny day.”
Slide 73
Other General String Utilities (Cont.) void *memset (void * s, int c, size_t n):
copies c in the 1st n elements of s and returns pointer of s
Example: char s[] = “This is a sunny day.”;
memset (s, ‘c’,6); returns pointer of “sssssss a sunny day.”
Slide 74
Pass Function as Argument The name of the function is a pointer,
passing a function is just passing a pointer
Slide 75
Pass Function as Argument (Cont.) Example: Write a function that calculate
the average of any double function f(x), where x = m, …, n (Cont.)
To find the average of sin (5), .., sin (10), we useaverage (sin, 5, 10);
To find the average of sqrt(10),…, sqrt(100), we use
average (sqrt, 10, 100);
Slide 76
Pass Function as Argument (Cont.) Example: Write a function that calculate
the average of any double function f(x), where x = m, …, n
// The function header can also be// double average (double f(double), int m, int n)double average (double (*f)(double), int m, int n){
int i;double sum=0.0;
for (i=m; i<=n; ++i) sum += f(i);
return sum/(n-m);}
Slide 77
Pass Function as Argument (Cont.) Example: Find
Using the trapezoidal rule
b
adx
x
1
Slide 78
Array Out of Bound When array index is out of bound, you willThe undesired memory:
ExampleOutput
Buffer overflow Attack:http://www.youtube.com/watch?
v=CDCEBKnrMxc&fmt=22Heap Overflow Attack: https://www.youtube.com/watch?v=2W4tuxHcOnE
Slide 79
Dynamic Memory Allocation Allocate n memory with a type Use function defined in stdlib.h
malloc (n*sizeof(type)): more efficient, do not initialize all memory
calloc(n, sizeof(type)): less efficient,will initialize all memory
Always check request memory is successful. If successful, return pointer to the n memory base_pointer with the generic type void *
Need to free spaces after finish function call by free(base_pointer);
Slide 80
Dynamic Memory Allocation (Cont.) Example:
int *a;
if (a=calloc(5, sizeof(int))){ a[0]=10; a[1]=20; a[2]=30; a[3]=40; a[4]=50;}else printf(“Error, request memory are not available.\n”);
Slide 81
Array of Pointers (Array of Strings) Store array of strings: save space Example:Assume that array w has 5 cells, each stores an address of strings as follows:w[0]=100=address of string “this”w[1]=200=address of string “is”w[2]=300=address of string “a”w[3]=400=address of string “snow”w[4]=500=address of string “day”
Slide 82
Array of Pointers (Cont.) Example: (Cont.)
The addresses of w are as follows:
address of w[0]=1000
address of w[1]=1004
address of w[2]=1008
address of w[3]=1012
address of w[4]=1016
Slide 83
Array of Pointers (Cont.) Example: (Cont.)
There are 3 methods to do bubble sort for array w.
Method 1 is the most efficient one.
Slide 84
Array of Pointers – Method 1 (Cont.) Example: (Cont.)To use bubble sort to sort the array w:void sort_strings (char *w[], int n){ int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j)
if (strcmp(w[i],w[j])>0) swap (&w[i], &w[j]);
}
Slide 85
Array of Pointers – Method 1 (Cont.) Example: (Cont.)To use bubble sort to sort the array w: (Cont.)
for i=0 and j=1, if (strcmp(w[i],w[j])>0)
This means strcmp(100, 200) which is required by Function strcmp to compare the contents ofaddresses 100 and 200
swap (&w[i], &w[j]);This sends in addresses 1000 and 1004 to function swap}
Slide 86
Array of Pointers – Method 1 (Cont.) Example: The swap function is written as
(Cont.) void swap (char **s, char **t){ char *tmp; tmp=*s; *s=*t; *t=tmp;}
Slide 87
Array of Pointers – Method 1 (Cont.) Example: (Cont.) You may also write it asvoid swap (char *s[], char *t[]){ char *tmp; tmp=*s; *s=*t; *t=tmp;}
Slide 88
Array of Pointers – Method 1 (Cont.) Example: The detailed function call (Cont.) void swap (char **s, char **t){/*The line above has char **, which means address of address (or address of pointers).For the 2 slides before, s=1000, t=1004 */
char *tmp; // tmp contains address tmp=*s; // *s=*1000=100 *s=*t; // *t=*1004=200 *t=tmp;} // The swap here swaps addresses 100 and 200
Slide 89
Array of Pointers – Method 1 (Cont.) Example: (Cont.)Instead of swapping address of w[i] and w[j], we can swap the string directly (a less efficient way):void sort_strings (char *w[], int n){ int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j)
if (strcmp(w[i],w[j])>0) swap (w[i], w[j]);
}
Slide 90
Array of Pointers – Method 1 (Cont.) Example: The swap function is written as
(Cont.) void swap (char *s, char *t){ char *tmp; strcpy(tmp, s); strcpy(s, t); strcpy(t, tmp);}
Slide 91
Array of Pointers – Method 1 (Cont.) Example: (Cont.)After bubble sort, the array w contains
w[0]=300=address of string “a”w[1]=500=address of string “day”w[2]=200=address of string “is”w[3]=400=address of string “snow”w[4]=100=address of string “this”
Slide 92
Array of Pointers – Method 1 (Cont.) Example: (Bubble sort of words)
1. Swap (direct addressing), word: static array2. Swap (in-direct addressing), word: static
array: efficient
1. Swap (in-direct addressing), word: dynamic array: efficient Program, Data
Slide 93
Array of Pointers – Method 2 Another way to write sort_strings is as below:To use bubble sort to sort the array w:void sort_strings (char *w[], int n){ int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j)
if (*w[i]> *w[j]) swap (w[i], w[j]);
}
Slide 94
Array of Pointers – Method 2 (Cont.) Another way to write sort_strings is as below:For i=1 and j=2,
if (*w[i]> *w[j])This means the content of address 100 (The 1st character at address 100)> that of address 200
swap (w[i], w[j]);This sends addresses 100 and 200 into function swap
Slide 95
Array of Pointers – Method 2 (Cont.) Example: The swap function is (Cont.) void swap (char *s, char *t){ char tmp; tmp=*s; *s=*t; *t=tmp;}
Slide 96
Array of Pointers – Method 2 (Cont.) Example: The detailed function call (Cont.) void swap (char *s, char *t){/* s=100, t=200 */ char tmp; tmp=*s; // *s=*100=‘t’ *s=*t; // *t=200=‘i’ *t=tmp;} // This swaps only the 1st char ofstings “this” and “is”
Slide 97
Array of Pointers – Method 2 (Cont.) Example: (Cont.)After bubble sort, the array w contains
w[0]=100=address of string “ahis”w[1]=200=address of string “ds”w[2]=300=address of string “i”w[3]=400=address of string “snow”w[4]=500=address of string “tay”
Slide 98
Array of Pointers – Method 3 Example: (Cont.)To use bubble sort to sort the array w:void sort_strings (char *w[], int n){ int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j)
if (strcmp (w[i],w[j])>0) swap (&w[i], &w[j]);
}
Slide 99
Array of Pointers – Method 3 (Cont.) Example: The swap function is written as
(Cont.) void swap (char **s, char **t){ char tmp; tmp=**s; **s=**t; **t=tmp;}
Slide 100
Array of Pointers – Method 3 (Cont.) Example: It can also be written as (Cont.)void swap (char *s[], char *t[]){ char tmp; tmp=**s; **s=**t; **t=tmp;}
Slide 101
Array of Pointers – Method 3 (Cont.) Example: The detailed function call (Cont.) void swap (char **s, char **t){/*The line above has char **, which means address of address (or address of pointers).For the 2 slides before, s=1000, t=1004 */
char tmp; // tmp contains content of string tmp=**s; // **s=**1000=*100=‘t’ **s=**t; // **t=**1004=*200=‘i’ **t=tmp;} // The swap here also swaps the 1st char of contents of addresses 100 and 200
Slide 102
Sort Array of strings- Method 4 Problem: In the previous license example, we want to sort array of strings license[] according to the frquencies of each licenseint main (void){
… sort_strings (license, frequency, count); …}
Slide 103
Sort Array of strings- Method 4 (Cont.)void sort_strings (char w[][9], int f[], int n){
int i, j;
for (i=0; i<n; ++i)for (j=i+1; j<n;++j)
if (f[i]<f[j]){
swapString (&w[i], &w[j]); // swap license arrayswapInt(&f[i], &f[j]); // swap frequency array
}}
}
Slide 104
Sort Array of strings- Method 4void swapString (char s[][9], char t[][9]){
char tmp[9]="";
strcpy(tmp,*s);strcpy(*s,*t);strcpy(*t,tmp);
}
Slide 105
Sort Array of strings- Method 4void swapInt (int *a, int *b){
int tmp;
tmp=*a;*a=*b;*b=tmp;
} Complete Example: Sort Names and Grades by Grades,
Sort Names and Grades by Lastname, Data
Slide 106
Command Line Arguments 3 arguments for main() function
argc: total number of arguments including the
command argv[]: array of pointers
argv[0]: contains command argv[1]: contains 1st argument after command
… etc env[]: array of environment variables
Slide 107
Command Line Arguments (Cont.) Example:// use the following function header// int main(int argc, char ** argv, char **env)orint main (int argc, char * argv[], char *env[]){ int i; for (i=0;i<argc;++i) printf(“argv[%d]=%s\n”,i, argv[i]); for (i=0;env[i] != NULL;++i) printf(“env[%d]=%s\n”,i, env[i]); return 0;}
Slide 108
Command Line Arguments (Cont.) Class Example: Print All Arguments
Example1
Example2
Example3
Example4 (Hint to Extra HW #1):
use strtok function
Slide 109
Practice 1
Given int i=3, j=5,*p=&i,*q=&j,*r; double x;
Find the values of the following table:
Expression Value
________ _____
p == &i
** &p
r=&x
7**p/*q+7
*(r=&j)*=*p *r=
Slide 110
Practice 1 (Answer)
Given int i=3, j=5,*p=&i,*q=&j,*r; double x;
Find the values of the following table:
Expression Value
________ _____
p == &i 1
** &p 3
r=&x 1
7**p/*q+7 11
*(r=&j)*=*p *r= 15
Slide 111
Practice 2
Given char s1[]="beautiful big sky country";
s2[]="how now brown cow";
Find the values of the following table:
Expression Value
------------- ------
strlen(s1)
strlen(s2+8)
strcmp(s1,s2)
printf("%s",s1+10);
strcpy(s1+10, s2+8); strcat(s1,"s!"); printf("%s",s1);
Slide 112
Practice 2 (Answer)
Given char s1[]="beautiful big sky country"; s2[]="how now brown cow"; Find the values of the following table: Expression Value------------- ------strlen(s1) 25strlen(s2+8) 9strcmp(s1,s2) < 0printf("%s",s1+10); “big sky country”strcpy(s1+10, s2+8); strcat(s1,"s!");printf("%s",s1);
“beautiful brown cows!”
Slide 113
Practice 3
Given int a[3][5]
(1) Is a== &a[0]?
(2) Is a == &a[0][0]?
(3) Find which ones in the following are not the
same as a[i][j]?
*(a[i]+j)
*(&a[0][0]+5*i+j)
a[i] + j
(*(a+i))[j]
*((*(a+i))+j)
Slide 114
Practice 3 (Cont.)
Answer:
(1) Yes
(2) No
(3) a[i] + j is different, the rest are the same
Example
Slide 115
Practice 4Use command line to execute a program called mycp using
mycp indata outresult If your main function header is
int main(int argc, char *argv[ ]) What's the value of the following? argc = argv[1][2] argv[2][2] (*argv)[0]= *(argv+1)[0]=**argv=
Slide 116
Practice 4 (Answer)Use command line to execute a program called mycp using
mycp indata outresult If your main function header is
int main(int argc, char *argv[ ]) What's the value of the following? argc = 3argv[1][2] = ‘d’argv[2][2] = ‘t’(*argv)[0]= ‘m’*(argv+1)[0]= ‘i’**argv= ‘m’
Slide 117
Practice 4 (Explanation) Example: (Cont.)
The command line arguments are in the array
argv which contains
*argv=argv[0]=100=address of string “mycp”
*(argv+1)=argv[1]=200=address of string “indata”
(argv+2)=argv[2]=300=address of string “outresult”
Slide 118
Practice 5
Given char c='A', s[]="Blue moon!"; Show what to be printed? statement print out ________ _______ printf("%c",c) printf("%2c",c) printf("%-3c",c) printf("%s",s) printf("%3s",s) printf("%.6s",s) printf("%-11.8s",s)
Slide 119
Practice 5 (Answer)
Given char c='A', s[]="Blue moon!"; Show what to be printed? (^ represents a blank)statement print out ________ _______ printf("%c",c) Aprintf("%2c",c) ^Aprintf("%-3c",c) A^^ printf("%s",s) Blue moon!printf("%3s",s) Blue moon!printf("%.6s",s) Blue mprintf("%-11.8s",s) Blue moo^^^
Slide 120
Appendix(1). Binary Search/* Purpose: use binary search to search the key on a sorted score array. If found, return the index. * If not found, return -1* * Input: key, sorted score array and the size n•* Output: either its index if found •or -1 if not found•*/
Slide 121
Appendixint binarySearch(int key, int score[50], int n) { int left=0, right=n-1; int middle;
while (left < right) {middle=(left+right)/2;if (key == score[middle])
return middle; // found key else
if (key > score[middle])left=middle+1; // key in right part
elseright=middle; // key in leftpart
} return -1; // key not found
}
Slide 122
Appendix(2). Selection Sortvoid selectionSort (int ar[], int n) { int i, j, minat, mi, tempn;
for (i=0;i<n-1;i++){minat=i;min = a[i];for(j=i+1;j<n ;j++) {// select min in array if (min > a[j]) {//ascending order for descending reverse
minat=j; //the position of the min elementmin=a[j];
} // if} // for jtemp=a[i] ; //swapa[i]=a[minat]; a[minat]=temp;
} // for i} // selection sort
Slide 123
References Deitel & Deitel: C How to Program, 4th ed.,
Chapter 6, 7 & 8, Prentice Hall