c programming lecture 20 arrays and strings. bubble sort void swap(int *,int *); void bubble(int...

19
C Programming C Programming Lecture 20 Lecture 20 Arrays and Strings Arrays and Strings

Upload: louis-kirkby

Post on 14-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

C ProgrammingC Programming

Lecture 20Lecture 20Arrays and StringsArrays and Strings

Page 2: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Bubble SortBubble Sort

void swap(int *,int *);

void bubble(int a[], int n) /* n is the size of a[] */{ int i, j;

for (i = 0; i < n; ++i) for (j = n - 1; i < j; --j) if (a[j-1] > a[j]) swap(&a[j-1], &a[j]);}

void swap(int *p, int *q);{ int tmp; tmp = *p; *p = *q; *q = tmp;}

Page 3: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Strings and PointersStrings and Pointers

In C, a In C, a stringstring is a is a one-one-dimensional arraydimensional array of type of type charchar. . • A character in a string can be A character in a string can be accessedaccessed either: either:– As an As an element of an arrayelement of an array, or , or – By making use of a By making use of a pointer to charpointer to char..

• The type The type pointer topointer to charchar is is conceptually conceptually a stringa string..

• A unique aspect of a string is the A unique aspect of a string is the use of the character value ‘use of the character value ‘\0\0’ to ’ to terminate the string.terminate the string.

Page 4: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

The End-of-String The End-of-String Sentinel \0Sentinel \0

In C, a string is terminated by In C, a string is terminated by the the end-of-string sentinelend-of-string sentinel \0\0 (the (the null characternull character).).• A A constant stringconstant string such as such as “abc”“abc”is is stored in memory as stored in memory as fourfour characters, characters, the last one being the last one being \0\0..

• The The length of the stringlength of the string “abc” is “abc” is 33, , but but size of the arraysize of the array that holds the that holds the string must be string must be at least 4at least 4..

Page 5: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Declaring a StringDeclaring a String

To declare an To declare an array of charactersarray of characters that will be used that will be used to store a to store a stringstring, you must allocate enough , you must allocate enough storage to:storage to:• Hold the Hold the maximummaximum number of characters number of characters that will be stored in the string.that will be stored in the string.

• Plus one bytePlus one byte (character) to hold (character) to hold the the null characternull character..

Page 6: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Example Declaration of a Example Declaration of a StringString

My name, Paul Higbee, has 11 My name, Paul Higbee, has 11 characters (including the characters (including the space), but storing my name space), but storing my name in as a string requires an in as a string requires an array of 12 characters.array of 12 characters.• So I would declareSo I would declare

char myname[12];char myname[12];

Page 7: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Inputting a String from the Inputting a String from the KeyboardKeyboard

How scanf() works with a string:How scanf() works with a string: #define MAX_SIZE 100#define MAX_SIZE 100 int main(void)int main(void) {{ char w[MAX_SIZE];char w[MAX_SIZE]; . . .. . . scanf(“%s”, w);scanf(“%s”, w);• FirstFirst scanf() positions the input stream to scanf() positions the input stream to an initial nonwhite space character.an initial nonwhite space character.

• SecondSecond, nonwhite space characters are read , nonwhite space characters are read in and placed in memory beginning at the in and placed in memory beginning at the base address of w.base address of w.

• The process The process stopsstops when awhen a white space white space charactercharacter oror EOFEOF is encountered.is encountered.– At that point a At that point a null characternull character is placed in is placed in memory (by the C system) to end the string.memory (by the C system) to end the string.

Page 8: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Example: Inputting a String Example: Inputting a String Using Using scanf()scanf()

Suppose you want a user to input their first Suppose you want a user to input their first and last names on a single line:and last names on a single line:char fname[20], lname[20];char fname[20], lname[20];. . .. . .printf(“Input your first and last names: “);printf(“Input your first and last names: “);scanf(scanf(““%s%s%s%s”, ”, fnamefname, , lnamelname));;

• When the user types their first and last name, When the user types their first and last name, then presses ENTER, scanf() will:then presses ENTER, scanf() will:– skip any spaces the user input before their first nameskip any spaces the user input before their first name– start reading characters into fnamestart reading characters into fname– stop when the space between names is reachedstop when the space between names is reached– place a \0 into the fname arrayplace a \0 into the fname array– skip the space(s) and start reading characters into lnameskip the space(s) and start reading characters into lname– stop reading characters into lname when \n is reachedstop reading characters into lname when \n is reached– place a \0 into lnameplace a \0 into lname

• Note that the spaces and \n are removed from the Note that the spaces and \n are removed from the input buffer but not stored in the strings.input buffer but not stored in the strings.

Page 9: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Example: Inputting a String Example: Inputting a String Using Using scanf()scanf()

printf(“Input your first and last names: “);printf(“Input your first and last names: “);scanf(scanf(““%s%s%s%s”, ”, fnamefname, , lnamelname));;

• When the user types their first and last When the user types their first and last name, then presses ENTER, scanf() will:name, then presses ENTER, scanf() will:– skip any spaces the user input before their skip any spaces the user input before their first namefirst name

– start reading characters into fnamestart reading characters into fname– stop when the space between names is reachedstop when the space between names is reached– place a \0 into the fname arrayplace a \0 into the fname array– skip the space(s) and start reading characters skip the space(s) and start reading characters into lnameinto lname

– stop reading characters into lname when \n is stop reading characters into lname when \n is reachedreached

– place a \0 into lnameplace a \0 into lname • Note that the spaces and \n are removed from Note that the spaces and \n are removed from the input buffer but not stored in the the input buffer but not stored in the strings.strings.

Page 10: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Initialization of StringsInitialization of Strings

Arrays, including character arrays,can Arrays, including character arrays,can be initialized.be initialized.However,the compiler allows a special syntax However,the compiler allows a special syntax for initialization of strings:for initialization of strings:

char s[] = “abc”;char s[] = “abc”;

is equivalent tois equivalent to

char s[] = {‘a’, ’b’, ‘c’, ‘\0’};char s[] = {‘a’, ’b’, ‘c’, ‘\0’};

When the string-specific first form is used, When the string-specific first form is used, the size of the string is one more than the the size of the string is one more than the string length in order to terminate the string length in order to terminate the string with the \0 null character.string with the \0 null character.

Page 11: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Initializing a Pointer-to-Initializing a Pointer-to-Character with a StringCharacter with a String

A A pointer-to-characterpointer-to-character can be can be initialized with a constant string, but initialized with a constant string, but the interpretation is different.the interpretation is different. char *p = “abc”;char *p = “abc”;• When a When a character pointercharacter pointer is initialized with is initialized with a a constant stringconstant string, the pointer simply stores , the pointer simply stores the the addressaddress where the constant string is where the constant string is stored in memory.stored in memory.

• When an When an arrayarray is initialized using a is initialized using a constant stringconstant string, the , the characters themselvescharacters themselves (including the null character) are stored in (including the null character) are stored in the array.the array.– The string constant itself remains in another The string constant itself remains in another location in memory.location in memory.

Page 12: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Passing Arguments to Passing Arguments to main()main()

We need to use We need to use arrays of pointers arrays of pointers to charto char to write programs that to write programs that use command line arguments.use command line arguments.• Two arguments, conventionally called Two arguments, conventionally called argcargc and and argvargv can be can be used with main()used with main() to communicate with the to communicate with the operating operating systemsystem..

Instead ofInstead of int main(void)int main(void)

we usewe use int main(int argc, char *argv[])int main(int argc, char *argv[])

Page 13: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

The Meaning of The Meaning of argcargc and and argvargv

In the header of main:In the header of main: int main(int int main(int argcargc, char *, char *argvargv[])[])• the the variablevariable argcargc provides a provides a count of command line argumentscount of command line arguments

• the the arrayarray argvargv is an array of is an array of pointers to charpointers to char– argvargv can be thought of as an can be thought of as an array array of stringsof strings..

Page 14: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

String Handling FunctionsString Handling Functions

The The standard librarystandard library contains contains many useful many useful string handling string handling functionsfunctions..• All All requirerequire that strings passed as that strings passed as arguments be arguments be null-terminatednull-terminated..

• All All returnreturn either an either an integerinteger value or value or a a pointer to charpointer to char..

The The prototypesprototypes for the string for the string functions are in functions are in string.hstring.h..

Page 15: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Some String Handling Some String Handling FunctionsFunctions

char *strcat(char *s1, const char *s2);char *strcat(char *s1, const char *s2);• strcat() strcat() concatenatesconcatenates s2 onto the end of s1 s2 onto the end of s1• You must ensure that s1 allocated enough You must ensure that s1 allocated enough space to hold the result.space to hold the result.

• The string s1 is returned.The string s1 is returned. int strcmp(const char *s1, const char *s2);int strcmp(const char *s1, const char *s2);

• An An integer is returnedinteger is returned that is less than, that is less than, equal to, or greater than zero, equal to, or greater than zero, depending ondepending on whether s1 is lexicographically less than, whether s1 is lexicographically less than, equal to, or greater than s2.equal to, or greater than s2.

Page 16: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Two More String Handling Two More String Handling FunctionsFunctions

strcpy(char *s1, const char *s2);strcpy(char *s1, const char *s2);• The string s2 is copied into s1 until the \0 The string s2 is copied into s1 until the \0 is moved.is moved.

• Whatever exists in s1 is overwritten.Whatever exists in s1 is overwritten.• s1 must have enough space to hold the s1 must have enough space to hold the result.result.

• s1 is returned.s1 is returned.

unsigned strlen(const char *s);unsigned strlen(const char *s);• A count of the number of characters before \A count of the number of characters before \0 is returned.0 is returned.

Page 17: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Examples Using String Handling FunctionsDeclarations and Initializationschar s1[] = “beautiful big sky country”, s2[] = “how now brown cow”;Expression Valuestrlen(s1) 25strlen(s2 + 8) 9strcmp(s1, s2) negative integer

Statements What is Printedprintf(“%s”, s1 + 10); big sky countrystrcpy(s1 + 10, s2 + 8);strcat(s1, “s!”);printf(“%s”, s1); beautiful brown cows!

Page 18: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

Common Programming Common Programming ErrorsErrors

Overrunning the bounds of a string.Overrunning the bounds of a string.• It is the It is the programmer’s responsibilityprogrammer’s responsibility to make to make sure enough space is allocated for a string.sure enough space is allocated for a string.

• Don’t forget to allow space for the null Don’t forget to allow space for the null character.character.

• Can easily occur when strcat() is used.Can easily occur when strcat() is used.

Using Using ‘a’‘a’ when when “a”“a” should be used. should be used.• ““a” is a” is stored asstored as two characters two characters‘a’‘a’ and and ‘\0’‘\0’..

If str is a string variable, then use If str is a string variable, then use scanf(“%s”, scanf(“%s”, strstr); not scanf(“%s”, ); not scanf(“%s”, &str&str) ) to input a string.to input a string.

Page 19: C Programming Lecture 20 Arrays and Strings. Bubble Sort void swap(int *,int *); void bubble(int a[], int n) /* n is the size of a[] */ { int i, j; for

System ConsiderationsSystem Considerations

An ANSI C, string constants that are separated An ANSI C, string constants that are separated by zero or more white space characters are by zero or more white space characters are concatenated by the compiler into one long concatenated by the compiler into one long string.string.• Traditional C does not do this.Traditional C does not do this.

ExampleExample

char *long_string;char *long_string;

long_string = “A list of words:\n”long_string = “A list of words:\n”

“ “\n”\n”

“ “ 1 abacus\n”1 abacus\n”

“ “ 2 bracelet\n”2 bracelet\n”

“ “ 3 cafeteria\n”;3 cafeteria\n”;