390 likes | 591 Views
IPC144 Session 15 The C Programming Language. 1. Objectives To define arrays within the C language To use arrays in a C program To pass arrays between functions Define what a string is List the three methods strings can be stored in a computer. Use arrays to store strings
E N D
IPC144 Session 15 The C Programming Language 1
Objectives • To define arrays within the C language • To use arrays in a C program • To pass arrays between functions • Define what a string is • List the three methods strings can be stored in a computer. • Use arrays to store strings • List the standard C functions for manipulating strings • List the parameters for the C string functions, and their restrictions • Use the C string functions to manipulate strings 2
The C Language • Arrays • Recall from or earlier discussions of Arrays, that we will be dealing with one-dimensional arrays (like a column of an Excel spreadsheet). • A one-dimensional array is also called a list or a vector. • Each element is numbered uniquely • For C we will use the same notation we used in flowcharts: • tableName[index] • the tableName is a variable, and therefore you apply the variable naming standards when declaring a table. • the index is the element number • In C, the index always start at zero 3
The C Language Arrays, continued One dimensional tables If a table called myTab contained: element#element 0 Red 1 Orange 2 Yellow 3 Green 4 Blue 5 Violet myTab[0] contains Red myTab[4] contains ?? 4
The C Language Arrays, continued What is the data type of a table? The data type can be any of the types we discussed- the compiler uses this information so that it knows how to interpret the data once it gets there How are arrays stored inside the computer? Arrays are stored in contiguous memory locations, where the first location is pointed to by a variable that knows how to get to the start of the list of elements How are arrays declared? 5
The C Language Arrays, continued Anatomy of an array declaration: int myTab[5]; The maximum number of elements in the array (numbered 0 to n - 1) The name of the table- following the variable naming standards Data type of the array This is an implicit declaration of a pointer (myTab) that points to a fixed block of memory that will contain the elements of the array. This means that when you use the array name by itself, you are using a pointer variable! 6
The C Language Arrays, continued Write a program that reads 10 floats from the user and stores them into an array. 7
The C Language Arrays, continued #include <stdio.h> #define ARRAY_SIZE 10 int main(void) { int counter, ch; float theArray[ARRAY_SIZE]; for (counter = 0; counter < 10; counter = counter + 1) { scanf("%f", &theArray[counter]); while((ch = getc(stdin)) != EOF && ch != '\n'); } for (counter = 0; counter < ARRAY_SIZE; counter = counter + 1) printf("theArray[%d] = %1.2f\n", counter, theArray[counter]); } Something new: while((ch = getc(stdin)) != EOF && ch != '\n'); This causes the computer to discard anything that happens to have been left in the keyboard buffer after the last read - essentially this cleans up in preparation of another keyboard read. 8
The C Language Arrays, continued What is the most efficient method to pass an array to a function, in order that the function may change the contents of one of the elements (or many elements) of the array? Pass-by-reference. There are two possible syntax rules for declaring a pointer to an array in a function prototype or a function declaration (shown below): myFunc(int mytab[]) { } or myFunc(int *myTab) { } The following is a program written to use a function to print a table: 9
The C Language Arrays, continued #include <stdio.h> #define TAB_SIZE 10 void printFunction(int tbl[]); int main(void) { int i; int table[TAB_SIZE]; for (i = 0; i < 10; i = i + 1) { table[i] = i * 2; } printFunction(table); } void printFunction(int tbl[]) { int i; for (i = 0; i < TAB_SIZE; i= i + 1) printf("table[%d] = %d\n", i, tbl[i]); } 10
The C Language Arrays, continued Write a program that reads 5 numbers from the user and stores them into a 5 element array. Create a function that flips the array upside down. The first element becomes the last, the last becomes the first. The second element becomes the second last, the second last element becomes the second and so on. 11
Strings 12
The C Language Strings Strings What is a string? Strings are a collection of characters treated as a unit A word, sentence, paragraph or book can all be considered strings Even a single character can be considered a string- we shall see why shortly There is also an allowance for an empty string- that is a string containing no characters 13
The C Language Strings Fixed length Variable length Length controlled Delimited Strings, continued How are strings defined to the computer? 14
The C Language Strings Fixed length Variable length Length controlled Delimited Non character data Strings, continued Fixed Length A R I S T O T L E 15
The C Language Strings Fixed length Variable length Length controlled Delimited Length Strings, continued Length Controlled 9 A R I S T O T L E 16
The C Language Strings Fixed length Variable length Length controlled Delimited Delimiter Strings, continued Delimited A R I S T \0 O T L E 17
The C Language Delimiter Strings, continued We have used the '\n' in our programs. C identifies this as the new-line character. The ‘\0’ is another ‘special’ character in C- it represents the ‘null’ character It is one of those strange things about computers - they need to have something that represents nothing- null The null character, as far as the computer is considered, is a legitimate, normal character A R \0 I S T O T L E 18
The C Language Strings, continued If we remember the char data-type, it can contain ‘letters’ of the ASCII alphabet zero, in the ASCII alphabet, is the null character When programming in C there is a difference between how strings are represented and how single characters are represented 19
The C Language Strings, continued Character Data The data type for character data is char We can assign any of the 256 ‘letters’ of the ASCII alphabet to a char We can assign the ‘letter’ by using its numeric representation: char myChar; myChar = 65; We can assign the ‘letter’ by enclosing it in single quotes: char myChar; myChar = ‘A’; The above assignments perform the same action 20
The C Language Strings, continued String Data The data type for each character of the string is char The string is really an array of char data types We represent a string by enclosing it in double quotes: "this is a string" "" The second example is an empty string, or null string In both cases there is an IMPLICIT null character terminating the string 21
The C Language Strings, continued What does the string look like in memory? Based on these definitions being found in your program: ... char myString[20]; ... strcpy(myString, “this is a string”); ... The strcpy() is a predefined function that performs a STRingCoPY - it is like saying, in pseudocode: myString = "this is a string" ... t h i t s i s a s r i n g \0 ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Memory Reserved for myString 22
The C Language Strings, continued When deciding on how much memory to reserve for a string be sure to include one position for the null-terminator What would be the result of: myString[8] = '1'; On the following string in memory: ... t h i t s i s a s r i n g \0 ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Memory Reserved for myString 23
The C Language Strings, continued When deciding on how much memory to reserve for a string be sure to include one position for the null-terminator What would be the result of: myString[8] = 0; On the following string in memory: ... t h i t s i s 1 s r i n g \0 ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Memory Reserved for myString 24
The C Language Strings, continued Formatted output of strings - printf() A new conversion code is used: %s This tells the compiler to treat the array as a string of characters The function will print the string up to but not including the null-terminating character '\0' The flags and minimum width attributes can still be used Based on what you already know, what does the following mean? (assuming txnDesc has been declared a string) printf(“%-64s\n”, txnDesc); 25
The C Language • Strings, continued • Unformatted output of strings - puts() • The function prototype of puts() is: • int puts(char *ptrString); • If the function was successful, it returns a value >= 0 (a non-negative integer) • If the function failed, it returns EOF • EOF is a value defined by the compiler through a #define statement • it is a value < 0 • This function will AUTOMATICALLY output a new-line character after outputting all of the characters of the string 26
The C Language Strings, continued Formatted input of strings - scanf() Again, the %s conversion code is used The following statement will read a string of data up to the first white-space character: scanf("%s", myString); The function stores the new-line character (if encountered) 27
The C Language Strings, continued Consider the following code: #include <stdio.h> void main(void) { char strData[10]; scanf(“%s”, strData); printf(“Read: %s\n”, strData); } What would happen if the user typed in: a_very_long_and_arduous_journey,_is_this_course_on_C! 28
The C Language Strings, continued A better solution would be: #include <stdio.h> void main(void) { char strData[10]; scanf(“%9s”, strData); /* remember to leave a spot for the null */ printf(“Read: %s\n”, strData); } Now what would happen if the user typed in: a_very_long_and_arduous_journey,_is_this_course_on_C! 29
The C Language • Strings, continued • Unformatted input of strings - gets() • The function prototype of gets() is: • char *gets(char *ptrString); • This function will AUTOMATICALLY replace the new-line character with a null-terminator • If the function was successful, it returns a pointer to the same input string • If the function was unsuccessful, it returns NULL • NULL is a value defined by the compiler through a #define statement • it is a pointer to nothing • THIS IS A DANGEROUS FUNCTION AS YOU CAN EASILY CORRUPT MEMORY WITH AN UNCONTAINED READ – a better function is fgets() which will be introduced with file processing. 30
The C Language Strings, continued Predefined string manipulation commands: They all have the same basic format strxxx( parameters ) When working with strings, the computer will do NO checking on lengths It your responsibility to ensure that when you manipulate a string you do not overrun memory There is a specific header file associated with the predefined string functions: #include <string.h> 31
The C Language Strings, continued String Copy: char *strcpy(char *stringTo, char *stringFrom); This function takes a string pointed to by stringFrom and copies it to the location pointed to by stringTo (including the null-terminator) The function returns a pointer to stringTo The following is an example of memory overrun: #include <stdio.h> #include <string.h> void main(void) { char strTo[5]; char strFrom[15]; strcpy(strFrom, “This fails”); strcpy(strTo, strFrom); } 32
The C Language Strings, continued String-Number Copy: char *strncpy(char *stringTo, char *stringFrom, int size); This function copies no more than size characters If stringFrom is less than size, then stringTo will be padded to size characters using nulls If stringFrom is greater than size, then only size characters will be copied - NO null-terminator will be placed in stringTo 33
The C Language Strings, continued String Length: int strlen(char *string); This function returns the number of characters in the string (not including the null-terminator) 34
The C Language • Strings, continued • String Compare: • int strcmp(char *string1, char *string2); • This function will compare two strings character-by-character • If the two strings are identical, the function returns zero • Otherwise, it returns • a value < 0 if string1 < string2, or • a value > 0 if string1 > string2 • You need to reference an ASCII table to determine the order, or collating sequence, of the 'letters' • For example 'a' > 'A' according to the ASCII table 35
The C Language Strings, continued String-Number Compare: int strncmp(char *string1, char *string2, int size); This function will compare two strings character-by-character The test will stop when a null-terminator is encountered, OR size characters of string1 have been tested - whichever occurs first 36
The C Language Strings, continued String Concatenate: char *strcat(char *stringTo, char *stringFrom); This function will concatenate stringFrom to the end of stringTo Remember that there must be enough memory set aside to contain both the contents of stringTo and stringFrom The function returns a pointer to stringTo The null-terminator in stringTo is replaced by the first character of stringFrom All of stringFrom is copied to the end of stringTo until reaching the null-terminator of stringFrom 37
The C Language Strings, continued String-Number Concatenate: char *strncat(char *stringTo, char *stringFrom, int size); If the length of stringFrom is less than size, then the function will behave as if the strcat() function was used If the length of stringFrom is greater than size, then size characters are appended to stringTo followed by a null-terminator 38
The C Language Strings, continued What would be the output of the following program: #include <stdio.h> #include <string.h> void main(void) { char str1[10]; char str2[10]; strcpy(str1, “Testing”); printf(“Length is %d\n”, strlen(str1)); strcpy(str2, str1); printf(“String2 = %s\n”, str2); if (strcmp(str1, str2) == 0) printf(“Both strings are the same\n”); str1[4] = ‘\0’; strncat(str1, str2, 3); printf(“String1 is now: %s\n”); if (strncmp(str1, str2, 4) == 0) printf(“The strings are still equal\n”); } 39