Chapter 5 Array, Pointers and Strings

1 / 120
About This Presentation
Title:

Chapter 5 Array, Pointers and Strings

Description:

Chapter 5 Array, Pointers and Strings. By C. Shing. ITEC Dept ... 100 is not allowed &a is not allowed a is not allowed. a = (int *) 100 is not allowed ... – PowerPoint PPT presentation

Number of Views:261
Avg rating:3.0/5.0
Slides: 121
Provided by: radf7
Learn more at: http://www.radford.edu

less

Transcript and Presenter's Notes

Title: Chapter 5 Array, Pointers and Strings


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_sizecoulmn_size

5
Array (Cont.)
  • Has index (or indices) starting from 0
  • to access each memory
  • 1-dimension specify the content at index
  • array_nameindex
  • Example
  • type array_name array_size
  • declare memory array_name0, array_name1,
    ,
  • array_namearray_size-1
  • 2-dimension specify the content
  • at row_index and column_index
  • array_namerow_indexcolumn_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_namearray_size initial values
  • 2-dimension
  • type array_namerow_sizecolumn_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 a4,3,2,1
  • Then a04, a13, a22, a31
  • 2-dimension
  • int a34
  • 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 a4 10,11,12,13, 20,21,22,23,
  • 30,31,32,33
  • Then a0010, a0111, a0212,
    a0313, , ,
  • a2030, a2131, a2232,
    a2333

9
Array (Cont.)
  • Initialization (Cont.)
  • Example (Cont.)
  • 1-dimension
  • int a 4 4,3
  • Then a04, a13, a20, a30
  • 2-dimension
  • int a34
  • 10, 20,21,22,
  • 30,31
  • Then a0010, a01a02a030,
    a2030,
  • a2131, a22a230

10
Array (Cont.)
  • Initialization (Cont.)
  • Example Initialize the whole array
  • 1-dimension
  • int a 4 0
  • Then a00, a10, a20, a30
  • 2-dimension
  • int a34
  • 0
  • Then a00a01a02a03 a20
  • a21a22a230

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 (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_name0
  • The array_name stores array_name0
  • The (array_namei) stores array_namei
  • Example
  • int aN, p
  • p a // p a0
  • p ai // pai
  • Note if the address of the array a is 1000, then
    p contains
  • the address 1000 isizeof(int), which is not
    1000i
  • Example

17
Array and Pointer Relation (Cont.)
  • Do not attempt to change the address of the array
  • Example
  • int a100, 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_sizecolumn_size
  • The base address is array_name00
  • The array_name stores array_name0
  • beginning address of 1st row
  • (different from array_name00)
  • The (array_namei) stores array_namei

19
Array and Pointer Relation (cont.)
  • Example
  • int aMN, p
  • p a // p a0, where a0 is an array of N
    elements
  • // p is the array a0, which contains N
    elements
  • P ai // pai
  • Class Example

20
Array and Pointer Relation (cont.)
  • Array name stores address of the array (Cont.)
  • 2-dim
  • Question
  • int aMN, p
  • Can you use pointer p (where pa00)
  • to find aij?

21
Array and Pointer Relation (cont.)
  • Array name stores address of the array (Cont.)
  • 2-dim (Cont.)
  • int aMN, p
  • pa00
  • Answer
  • aij(piNj)

22
Array and Pointer Relation (cont.)
  • Array name stores address of the array (Cont.)
  • 2-dim
  • Question
  • int aMN, p
  • pa
  • Can you use pointer p to find aij?

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

24
Array and Pointer Relation (cont.)
  • Array name stores address of the array (Cont.)
  • 2-dim (Cont.)
  • int aMN, p
  • pa
  • Answer
  • aij ((pi))j or
  • aij ((pi)j)
  • Is the following correct?
  • aij (pij)
  • 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(an)
  • 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 a100
  • a00
  • byValue(a0)
  • printf(a0d,a0) // a00 is printed
  • void byValue(int b)
  • b100

31
Passing Array to Functions- by Reference
  • Example 1-dim
  • int a100, i
  • for (i0ilt100i)
  • aii
  • byReference(a)
  • for (i0ilt100i)
  • printf(add,i,ai) // a0100,
    a199, are printed
  • void byReference(int a) // a is a pointer
  • int i
  • for (i0ilt100i)
  • ai100-i // use pointerindex 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 lt 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 lt 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 vendorMAXSIZE4
  • input_data (vendor)
  • void input_data (double vendor)
  • int i, j
  • for (i0iltMAXSIZEi)
  • for (j0jlt4j)
  • scanf(lf, vendorij)

38
Class Example (Cont.)
  • Example (Cont.)
  • Answer
  • The bug is at
  • void input_data (double vendor)
  • And
  • void input_data (double vendor)
  • scanf(lf, vendorij)

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

40
Class Example (Cont.)
  • Example (Cont.)
  • Answer (Cont.)
  • Correction
  • define MAXSIZE 50
  • void input_data (double vendor4)
  • int main (void)
  • double vendorMAXSIZE4
  • input_data (vendor)
  • void input_data (double vendor4)
  • int i, j
  • for (i0iltMAXSIZEi)
  • for (j0jlt4j)
  • scanf(lf, vendorij)

41
Bubble Sort
  • Sort an array of int a0, , acount
  • 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 a100, i
  • void bubble_sort (int a, int n)
  • int i,j
  • for (i0iltni)
  • for (jn-1jgti--j)
  • swap (aj-1, aj) // swap aj-1 and aj

43
Passing Array to Functions- by Reference (Cont.)
  • Example (Another version of bubble sort)
  • 1-dim
  • int a100, i
  • void bubble_sort (int a, int n)
  • int i,j
  • for (i0iltn-1i)
  • for (j0jltn-i-1j)
  • if (ajgtaj1)
  • swap (aj, aj1) // swap aj and
    aj1

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
  • tmpa
  • ab
  • btmp

45
Passing 2D Array to Functions- by Reference
  • Example 2-dim
  • int a10100, i, j
  • for (i0ilt10i)
  • for (j0jlt100,j)
  • aijij
  • byRef (a)
  • for (i0ilt10i)
  • for (j0jlt100,j)
  • printf(addd,i,j,aij) //
    a00100, a0199, are printed
  • void byRef (int a100)
  • int i, j
  • for (i0ilt10i)
  • for (j0jlt100,j)
  • aij100-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 sstring 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
  • Examplechar pconstant
  • printf(s\n, p2) // nstant printed
  • printf(c\n, p5) // a printed
  • printf(c\n, (p4)) // 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) ss concatenate
    t
  • strcpy (char s, const char t)
  • scopy of t until \0 of t is reached
  • strcmp (char s, const char t)
  • lt0 if sltt
  • 0 if st
  • gt0 if sgtt
  • 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)
  • ss concatenate at most n characters of t
  • strncpy (char s, const char t, size_t n)
  • scopy 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
  • lt0 if sltt
  • 0 if st
  • gt0 if sgtt

51
String Functions (Cont.)
  • Example
  • char strcpy (char s, register const char t)
  • register char ps
  • while (pt)
  • return s

52
Keyboard Input Function - gets
  • Form gets (string_variable)
  • Read from keyboard into string_variable
  • until end of line or end of file
  • Example
  • char s80 // remember s is address, do not use
    char s
  • gets (s)
  • // sample dataa 100 -1.23 This is a sample data
  • // sa 100 -1.23 This is a sample data

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

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 sa 100 -1.23 This is a sample
    data

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 s80 // remember s is address
  • scanf(cdlfs, c, i, db, s)
  • // sample dataa 100 -1.23 This is a sample data
  • // ca, i100, db-1.23, sThis

56
Example - scanf
  • Program read characters into an arrays
  • (lname and fname) and convert them to strings
  • Data

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
  • 10d
  • Read in 10 digit number
  • 10c
  • Read in 10 characters
  • c
  • Skip any number of characters
  • Example Program, Data
  • Hint to Quiz 5, Hint Data

58
Keyboard Output Format Function - printf
  • Form printf(format, variable_address)
  • Format s, see those used in printf, see Chapter
    2

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 123
  • PLO4ME
  • 123456
  • AL-QADA2
  • PLO4ME
  • 123V456

60
Search Strings (Cont.)
  • int i
  • char plate9
  • char license10009
  • int frequency10000
  • int count0, index
  • // count of different licenses in license
    array
  • for (i0gets(plate)i)
  • index search(license, plate, count)

61
Search Strings (Cont.)
  • if (index -1)
  • strcpy(licensecount, plate)
  • else

62
Search Strings (Cont.)
  • int search (char license9, char plate, int
    count)
  • int i
  • for (i0 iltcount i)
  • if (strcmp (licensei,plate) 0)
  • return i // found plate in license array
  • return -1 // not found

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

64
Input and Output String Format Function sscanf
and sprintf (Cont.)
  • Example
  • char c
  • int i
  • double db
  • char s80, outstring80,
  • instringa 100 -1.23 This is a sample data
  • sscanf(instring,cdlfs, c, i, db, s)
  • //Then ca, i100, db-1.23, sThis
  • sprintf(outstring,cdlfs, c, i, db, s)
  • // print to outstring a 100 -1.23 This
  • Example, Data

65
Class Example
  • sscanf and gets
  • Example
  • Hint to HW
  • Substring of string from location 2 to 3 is tr

66
String Search Utilities
  • Need to include ltstring.hgt
  • char strchr(const char s, int c) return
    pointer to
  • the found character c in s. Returns NULL
    otherwise
  • Example
  • strchr(This is a sunny day., u) returns
    s11
  • size_t strcspn(const char s, const char range)
  • returns length of initial s that are not in the
    range
  • Example
  • strcspn(This is a sunny day., abcd)
    returns 8

67
String Search Utilities (Cont.)
  • size_t strspn (const char s, const char range)
  • returns length of initial s that are in range
  • Example
  • 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

68
String Search Utilities (Cont.)
  • char strrchr (const char s, int c)
  • returns pointer of the last found character c
    in s
  • Example
  • 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

69
String Search Utilities (Cont.)
  • char strtok (const char s, const char
    delimiter)
  • returns pointer of the token in s using the
    delimiter
  • and save the position of the next token
  • Example
  • char sThis is a sunny day.
  • char token
  • tokenstrtok(s, )
  • do
  • printf(tokens\n, token)
  • tokenstrtok(NULL, ) // must use this to
    get next token
  • while (token ! NULL)
  • The tokens printed are
  • This
  • is
  • a

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 t80
  • memcpy(t,s, 21)
  • returns pointer of t This is a sunny day.

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,s10, 3)
  • returns suns is a sunny day.

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 st,
  • -1 if sltt, 1 if sgtt
  • void memchr (const void s, int c, size_t n)
  • returns pointer of the 1st found c in the 1st n
    elements of s
  • Example
  • char s This is a sunny day.
  • memchr (s, u,16)
  • returns pointer of unny day.

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.

74
Pass Function as Argument
  • The name of the function is a pointer,
  • passing a function is just passing a pointer

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
    use
  • average (sin, 5, 10)
  • To find the average of sqrt(10),, sqrt(100),
  • we use
  • average (sqrt, 10, 100)

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 sum0.0
  • for (im iltn i)
  • sum f(i)
  • return sum/(n-m)

77
Pass Function as Argument (Cont.)
  • Example Find
  • Using the trapezoidal rule

78
Array Out of Bound
  • When array index is out of bound, you will
  • The undesired memory
  • Example
  • Output

79
Dynamic Memory Allocation
  • Allocate n memory with a type
  • Use function defined in stdlib.h
  • malloc (nsizeof(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)

80
Dynamic Memory Allocation (Cont.)
  • Example
  • int a
  • if (acalloc(5, sizeof(int)))
  • a010 a120 a230 a340 a450
  • else
  • printf(Error, request memory are not
    available.\n)

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
  • w0100address of string this
  • w1200address of string is
  • w2300address of string a
  • w3400address of string snow
  • w4500address of string day

82
Array of Pointers (Cont.)
  • Example (Cont.)
  • The addresses of w are as follows
  • address of w01000
  • address of w11004
  • address of w21008
  • address of w31012
  • address of w41016

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.

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 (i0 iltn i)
  • for (ji1 jltnj)
  • if (strcmp(wi,wj)gt0)
  • swap (wi, wj)

85
Array of Pointers Method 1 (Cont.)
  • Example (Cont.)
  • To use bubble sort to sort the array w (Cont.)
  • for i0 and j1,
  • if (strcmp(wi,wj)gt0)
  • This means strcmp(100, 200) which is required by
  • Function strcmp to compare the contents of
  • addresses 100 and 200
  • swap (wi, wj)
  • This sends in addresses 1000 and 1004 to function
    swap

86
Array of Pointers Method 1 (Cont.)
  • Example The swap function is written as (Cont.)
  • void swap (char s, char t)
  • char tmp
  • tmps
  • st
  • ttmp

87
Array of Pointers Method 1 (Cont.)
  • Example (Cont.) You may also write it as
  • void swap (char s, char t)
  • char tmp
  • tmps
  • st
  • ttmp

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, s1000, t1004 /
  • char tmp // tmp contains address
  • tmps // s1000100
  • st // t1004200
  • ttmp
  • // The swap here swaps addresses 100 and 200

89
Array of Pointers Method 1 (Cont.)
  • Example (Cont.)
  • Instead of swapping address of wi and wj,
  • we can swap the string directly (a less efficient
    way)
  • void sort_strings (char w, int n)
  • int i, j
  • for (i0 iltn i)
  • for (ji1 jltnj)
  • if (strcmp(wi,wj)gt0)
  • swap (wi, wj)

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)

91
Array of Pointers Method 1 (Cont.)
  • Example (Cont.)
  • After bubble sort, the array w contains
  • w0300address of string a
  • w1500address of string day
  • w2200address of string is
  • w3400address of string snow
  • w4100address of string this

92
Array of Pointers Method 1 (Cont.)
  • Example (Bubble sort of words)
  • Swap (direct addressing), word static array
  • Swap (in-direct addressing), word static array
  • efficient
  • Swap (in-direct addressing),
  • word dynamic array efficient
  • Program, Data

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 (i0 iltn i)
  • for (ji1 jltnj)
  • if (wigt wj)
  • swap (wi, wj)

94
Array of Pointers Method 2 (Cont.)
  • Another way to write sort_strings is as below
  • For i1 and j2,
  • if (wigt wj)
  • This means the content of address 100
  • (The 1st character at address 100)gt
  • that of address 200
  • swap (wi, wj)
  • This sends addresses 100 and 200 into
  • function swap

95
Array of Pointers Method 2 (Cont.)
  • Example The swap function is (Cont.)
  • void swap (char s, char t)
  • char tmp
  • tmps
  • st
  • ttmp

96
Array of Pointers Method 2 (Cont.)
  • Example The detailed function call (Cont.)
  • void swap (char s, char t)
  • / s100, t200 /
  • char tmp
  • tmps // s100t
  • st // t200i
  • ttmp
  • // This swaps only the 1st char of
  • stings this and is

97
Array of Pointers Method 2 (Cont.)
  • Example (Cont.)
  • After bubble sort, the array w contains
  • w0100address of string ahis
  • w1200address of string ds
  • w2300address of string i
  • w3400address of string snow
  • w4500address of string tay

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 (i0 iltn i)
  • for (ji1 jltnj)
  • if (strcmp (wi,wj)gt0)
  • swap (wi, wj)

99
Array of Pointers Method 3 (Cont.)
  • Example The swap function is written as (Cont.)
  • void swap (char s, char t)
  • char tmp
  • tmps
  • st
  • ttmp

100
Array of Pointers Method 3 (Cont.)
  • Example It can also be written as (Cont.)
  • void swap (char s, char t)
  • char tmp
  • tmps
  • st
  • ttmp

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, s1000, t1004 /
  • char tmp // tmp contains content of string
  • tmps // s1000100t
  • st // t1004200i
  • ttmp
  • // The swap here also swaps the 1st char of
  • contents of addresses 100 and 200

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 license
  • int main (void)
  • sort_strings (license, frequency, count)

103
Sort Array of strings- Method 4 (Cont.)
  • void sort_strings (char w9, int f, int n)
  • int i, j
  • for (i0 iltn i)
  • for (ji1 jltnj)
  • if (filtfj)
  • swapString (wi, wj) // swap license
    array
  • swapInt(fi, fj) // swap frequency
    array

104
Sort Array of strings- Method 4
  • void swapString (char s9, char t9)
  • char tmp9""
  • strcpy(tmp,s)
  • strcpy(s,t)
  • strcpy(t,tmp)

105
Sort Array of strings- Method 4
  • void swapInt (int a, int b)
  • int tmp
  • tmpa
  • ab
  • btmp
  • Complete Example Sort Names and Grades by
    Grades,
  • Sort Names and Grades by Lastname,
  • Data

106
Command Line Arguments
  • 3 arguments for main() function
  • argc total number of arguments including the
  • command
  • argv array of pointers
  • argv0 contains command
  • argv1 contains 1st argument after command
  • etc
  • env array of environment variables

107
Command Line Arguments (Cont.)
  • Example
  • // use the following function header
  • // int main(int argc, char argv, char env)
  • or
  • int main (int argc, char argv, char env)
  • int i
  • for (i0iltargci)
  • printf(argvds\n,i, argvi)
  • for (i0envi ! NULLi)
  • printf(envds\n,i, envi)
  • return 0

108
Command Line Arguments (Cont.)
  • Class Example Print All Arguments
  • Example1
  • Example2
  • Example3
  • Example4 (Hint to Extra HW 1)
  • use strtok function

109
Practice 1
  • Given int i3, j5,pi,qj,r double x
  • Find the values of the following table
  • Expression Value
  • ________ _____
  • p i
  • p
  • rx
  • 7p/q7
  • (rj)p r

110
Practice 1 (Answer)
  • Given int i3, j5,pi,qj,r double x
  • Find the values of the following table
  • Expression Value
  • ________ _____
  • p i 1
  • p 3
  • rx 1
  • 7p/q7 11
  • (rj)p r 15

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(s28)
  • strcmp(s1,s2)
  • printf("s",s110)
  • strcpy(s110, s28) strcat(s1,"s!")
    printf("s",s1)

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) 25
  • strlen(s28) 9
  • strcmp(s1,s2) lt 0
  • printf("s",s110) big sky country
  • strcpy(s110, s28) strcat(s1,"s!")printf("s",s
    1)
  • beautiful brown cows!

113
Practice 3
  • Given int a35
  • Is a a0?
  • Is a a00?
  • Find which ones in the following are not the
  • same as aij?
  • (aij)
  • (a005ij)
  • ai j
  • ((ai))j
  • (((ai))j)

114
Practice 3 (Cont.)
  • Answer
  • Yes
  • No
  • ai j
  • Example

115
Practice 4
  • 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
  • argv12
  • argv22
  • (argv)0
  • (argv1)0
  • argv

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 3
  • argv12 d
  • argv22 t
  • (argv)0 m
  • (argv1)0 i
  • argv m

117
Practice 4 (Explanation)
  • Example (Cont.)
  • The command line arguments are in the array
  • argv which contains
  • argvargv0100address of string mycp
  • (argv1)argv1200address of string indata
  • (argv2)argv2300address of string outresult

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)

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) A
  • printf("2c",c) A
  • printf("-3c",c) A
  • printf("s",s) Blue moon!
  • printf("3s",s) Blue moon!
  • printf(".6s",s) Blue m
  • printf("-11.8s",s) Blue moo

120
References
  • Deitel Deitel C How to Program, 4th ed.,
  • Chapter 6, 7 8, Prentice Hall
Write a Comment
User Comments (0)