Download presentation
Presentation is loading. Please wait.
Published byBritton Dickerson Modified over 6 years ago
1
Complex Data Types: Arrays & Structs Topic 7
Plan for the Day: Array Basics Strings (aka character arrays) Structures
2
Arrays
3
Array Overview ordered collection of items stored in contiguous memory
all items, called elements, are of same type array cannot be resized indexing starts at 0 – offset from beginning of array name of array is pointer (memory address) of 1st array element Declaration syntax: <elt-type> <array-name>[size]; sets aside size*sizeof(elt-type) bytes Example: int grades[80]; Example: int nums[5] = {1, 2, 3, 4, 5}; No index bounds checking size must be constant in C89. Starting in C99 can be determined at run-time, must be an int.
4
Can we solve this problem?
Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.6 4 days were above average.
5
Why the problem is hard We need each input value twice:
to compute the average (a cumulative sum) to count how many were above average We could read each value into a variable... but we: don't know how many days are needed until the program runs don't know how many variables to declare We need a way to declare many variables in one step.
6
Why the problem is hard We need each input value twice:
to compute the average (a cumulative sum) to count how many were above average We could read each value into a variable... but we: don't know how many days are needed until the program runs don't know how many variables to declare We need a way to declare many variables in one step. Solution: an array
7
Arrays Example: int arr[10] = {12, 49, -2, 26, 5, 17, -6, 84, 72, 3};
index 1 2 3 4 5 6 7 8 9 value 12 49 -2 26 17 -6 84 72 No out of bounds checking (example) element 0 element 4 element 9
8
Array declaration <type> <name>[size];
<type> <name>[ ] = {initial-values}; Example: int numbers[10] = {0}; index 1 2 3 4 5 6 7 8 9 value size – must be constant in ANSI C, can be variable expression (which is an int) in C99 and beyond
9
Initializing an Array An array initializer is a list of values enclosed in braces: int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; If initializer too short, remaining elements are set to 0: int a[10] = {0}; If an initializer is present, the length of the array may be omitted, and is determined by the compiler: int a[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Can declare these to be unchangeable if needed const int a[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
10
Accessing elements <name>[<index>] // access
<name>[<index>] = <value>; // modify Example: int numbers[10] = {0}; numbers[0] = 27; numbers[3] = -6; printf("%d\n", numbers[0]); if (numbers[3] < 0) { printf("Element 3 is negative."); } Valid index values: 0 to array's length - 1 index 1 2 3 4 5 6 7 8 9 value index 1 2 3 4 5 6 7 8 9 value 27 -6
11
Arrays and Loops Example: What's the sizeof (a) ?
int a[10], i; for (i = 0; i < 10 ; i++) {a[i] = 10 - i;} Warning: Array bounds in C are not checked; when a subscript goes out of bounds, the result is unpredictable. int a[10]; for (int i = 1; i <= 10; i++) a[i] = 2*i; // wrong! Arrays not automatically initialized to 0 unless they are global. sizeof(a) is # of bytes occupied by array (in our example, 10*sizeof(int)) sizeof(a[0]) is just sizeof(int) So sizeof(a)/sizeof(a[0[) is the size of the array or 10 What's the sizeof (a) ? What's the sizeof (a) / sizeof(a[0]) ?
12
Weather question Use an array to solve the weather problem:
How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.6 4 days were above average.
13
Weather Answer #include<stdio.h> // Reads temperatures from the user, computes average and # days above average int main() { int days; printf("How many days' temperatures? "); scanf(" %d", &days); int temps[days]; // array to store days' temps int sum = 0; // Read and store each day's temperature for(int i = 0; i < days; i++) { printf("Day %d's high temp: ", i+1); scanf(" %d", &temps[i]); sum += temps[i]; } double average = (double) sum/days; // see if each day is above average int count = 0; for(int i = 0; i < days; i++) { if(temps[i] > average) count++; } // report results printf("Average temp = %.1f\n", average); printf("%d days above average\n", count);
14
"Array mystery" problem traversal: An examination of each element of an array. What element values are stored in the following array? int a[] = {1, 7, 5, 6, 4, 14, 11}; for (int i = 0; i < sizeof(a)/sizeof(a[0])-1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } No length field .length in C. a.length doesn't work (it does in Java) index 1 2 3 4 5 6 value index 1 2 3 4 5 6 value 7 14 11
15
"Array mystery" problem traversal: An examination of each element of an array. What element values are stored in the following array? int a[] = {1, 7, 5, 6, 4, 14, 11}; for (int i = 0; i < sizeof(a)/sizeof(a[0])-1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } index 1 2 3 4 5 6 value 7 10 12 8 14 22 index 1 2 3 4 5 6 value
16
Array Arguments Often must pass length of array as well as array
Array argument: what's actually passed is pointer to (memory address) array int foo(int arr[]) { // sizeof won't tell us # of elts in arr parameter } Exercise: Write a function that takes an int array and the length of the array, and returns the sum of its elements. int sumArray(int a[], int len) { ...
17
Array Limitations You cannot resize an array
You cannot compare arrays with == or != char s[10], t[10]; if(s == t) {...} // s and t are memory addresses You cannot put array name on left side of assignment char s[10]; s = "abc"; // NO You cannot use sizeof to determine length of array parameter
18
Strings
19
Character Arrays Strings are represented as arrays of characters
The end of the string is specified with '\0' (aka null character) "hello" is represented with array {'h', 'e', 'l', 'l', 'o', '\0'} Examples: char myString[] = "hello"; char myString[10] = "hello"; char myString[] = {'h', 'e', 'l', 'l', 'o', '\0'}; Read about char type and ctype.h functions in textbook. More in recitation.
20
String Variables A "string" in C is a one-dim array of chars
Array length accounts for null character at end #define STR_LEN 80 char str[STR_LEN+1]; If string initializer does not fill array, remaining elements filled with null char ('\0') char date[9] = "June 14"; C doesn't support strings – it's lower level than other languages. Though extension libraries do give you string functions. Instead: array of characters C doesn't track length of string. The sentinel character \0 at end tells you when end of char array is reached. Make array big enough to include \0 date 'J' 'u' 'n' 'e' '1' '4' '\0'
21
Reading strings Don't exceed array's bounds
char name[10]; printf("Enter your name: "); scanf("%9s", name); Don't exceed array's bounds Leave room for null character at end of string name is the address of the array Output: Enter your name: MaryEberlein name: MaryEberl
22
Accessing the Characters
Function that counts and returns the number of spaces in a given argument string: int countSpaces(const char s[]) { int count, i; count = 0; for(i = 0; s[i] != '\0'; i++) { if(s[i] == ' ') count++; } return count; Can't change s
23
Comparing Strings Functions in header file string.h are used for string operations Cannot compare two strings with == int strcmp(char s[], char t[]) compares two strings in dictionary (lexicographic) order capital letters less than lowercase letters Returns negative if s comes before t Returns 0 if s is the same string as t Returns positive if s comes after t Examples: strcmp("Abe", "abe") // value is negative strcmp("123", "123") // value is 0 strcmp compares strings lexographically
24
String Manipulation: Copy & Concatenation
strcpy(str1, str2): copies str2 into str1 does not check that str1 is long enough to hold str2! char str1[10], str2[10]; strcpy(str2, "abcd"); // str2 contains "abcd" strcpy(str1, str2); //str1 contains "abcd" strncpy(str1, str2, n): copies up to n characters strcat(str1, str2): appends contents of str2 to end of str1 doesn't check that str1 is long enough strncat(str1, str2, n): appends up to n characters You can never put an array on the left side of an assignment. More about this later. Doesn't work: str2 = "abcd";
25
String Copy Output: char s[10] = "help";
char *foo = "War of the worlds"; strncpy(s, foo, 9); // copy 9 chars into positions 0-8 printf("s is %s\n, s); printf("length of s: %lu\n", strlen(s)); printf("Last char in s: %d\n", s[9]); Output: s is War of th length of s: 9 Last char in s: 0
26
strlen Function strlen(str): returns length of string stored in array str (not including null character at end) int len; char str[10] = "abc"; len = strlen(str); // len is 3
27
Search for chars and substrings
char *strchr(s, ch): returns pointer to first occurrence of ch in s, or NULL if ch is not found in s char *strstr(s1, s2): returns a pointer to first occurrence of s2 in s1
28
String Example Better to omit: != NULL Output:
#include<stdio.h> #include<string.h> int main() { printf("Does Alf come before alf? %s\n", strcmp("Alf", "alf") < 0 ? "yes" : "no"); printf("Does bass come before alf? %s\n", strcmp("bass", "alf")< 0 ? "yes" : "no"); char str1[10] = "hello"; char str2[10] = "world"; strncat(str1, str2, 4); printf("hello concatenated with world: %s\n", str1); int len = strlen(str1); printf("\"%s\" has length %d\n", str1, len); char str3[] = "hello"; // Does hello contain hell? if(strstr(str3, "hell") != NULL){ printf("hello contains hell\n"); } else printf("hello does not contain hell\n"); Better to omit: != NULL Notes: change strncat() call to strcat(str1, str2) – run-time error NULL pointer is guaranteed to compare equal to 0 Output: Does Alf come before alf? yes Does bass come before alf? no hello concatenated with world: helloworl "helloworl" has length 9 hello contains hell
29
Useful Functions (stdlib.h)
Description double atof(const char str[]) Converts string str to a double int atoi(const char str[]) Converts string str to an int double strtod(const char str[], char **endptr) Converts str to double (and returns the double), endptr points to the next character in str after the numerical value int abs(int x) returns the absolute value of integer x Also: int abs(int x): returns absolute value of an INT
30
Example Output: char str[10] = "3.14 This is pi"; char *restOfString;
double num; num = strtod(str, &restOfString); printf("The number is %lf\n", num); printf("The remaining string: %s\n", restOfString); Output: The number is The remaining string: This is pi
31
Example Other useful character handling functions in ctype.h: see 23.5, p. 612 isalnum(c) : is c alphanumeric? isalpha(c): is c alphabetic? isdigit(c): is c a decimal digit? islower(c): is c a lower-case letter? toupper(c): returns uppercase version of c if it's a letter, c otherwise #include<stdio.h> #include<ctype.h> #include<stdlib.h> ... // Q for queen, 10, 9, etc. char cardValue[3]; puts("Enter your card's value: "); scanf("%2s", cardValue); if(isdigit(cardValue[0])) { int value = atoi(cardValue); printf("Value: %d\n", value); } If card is 2, ..., 10, the value will be converted to an int and printed. If it's a J, Q, K, or A, it will not.
32
Exercise Write a version of the atoi function. Your function only needs to work on strings that contain positive integers. int myAtoi(char str[]) { // put your code here return result; }
33
Exercise int myAtoi(char str[]) { int result = 0; for(int i = 0; str[i] != '\0'; i++) { result = result*10 + str[i] - '0'; } return result; int main() { char str[] = "892"; int value = myAtoi(str); printf("%d\n", value); } Output: 892
34
command line arguments
35
Input on command line argc: # of arguments on command line
int main(int argc, char* argv[]) {…} argc: # of arguments on command line includes name of executable argv[]: array of strings on command line
36
Example Sample Run: int main(int argc, char *argv[]) {
for(int i = 0; i < argc; i++) { printf("arg %d = %s\n", i, argv[i]); } Sample Run: bash-3.2$ gcc commLine.c bash-3.2$ ./a.out one two three arg 0 = ./a.out arg 1 = one arg 2 = two arg 3 = three
37
Command Line Args Output? Note: argv[0] is ./prog argv[1] is 4
int main(int argc, char *argv[]) { if(argc < 2) printf("Need an integer!"); else { int n = atoi(argv[1]); int nums[n]; // legal in C99 for(int i = 0; i < n; i++) } nums[i] = i; } for(int i = 0; i < n; i += 2) printf("%d\n", nums[i]); Output? % gcc –o prog prog.c % ./prog 4 atoi() Note that loop update increments by 2. First loop creates nums[4] containing 0-3 Second loop prints nums[0], nums[2], i.e., 0 and 2 Note: argv[0] is ./prog argv[1] is 4
38
Exercise Write a program that takes integers on the command line and prints their sum. You may assume that all the command line arguments other than the executable name are integers. Example run: ./a.out 3 5 1 Sum = 9
39
structs
40
Structures struct: Collection of variables with one name
the variables are called members or fields may be different types Use structs to keep related data together pass fewer arguments return multiple values as a struct
41
Example A struct for data related to our class: Or use a typedef:
structure tag A struct for data related to our class: struct eeClass { int classNum; char meetingRoom[20]; char courseName[30]; }; Variable declaration: struct eeClass ee312; Member (or field) access: ee312.classNum = 312; Or use a typedef: typedef struct eeClass{ int classNum; char meetingRoom[20]; char courseName[30]; } EEClass; EEClass ee312; ee312.classNum = 312; strcpy(ee312.meetingRoom, "EER3");
42
structs Record containing related data values that are used together
Fields stored in contiguous memory Like an array, except: data values in struct have names access fields with "dot" operator, not [] Suppose you are writing a class scheduling system. You'd probably need to pass the same set of data to many functions. void catalog(char courseName[], int courseNumber, int secID) {…} Instead: combine that data in a struct Short for "structured data type" Bundle set of data into a single thing called a struct.
43
Structures Now your function might look like this:
struct UTCourse { char courseName[50]; int courseNumber; int secID; }; struct UTCourse EE312_00 = {"Software Design & Implementation I", 312, 16100}; Now your function might look like this: void catalog(struct UTCourse myClass) {…}
44
Field Access Use the dot operator to access fields (and the variable name) typedef struct name { char first[20]; char last[20]; } fullName; fullName me = {"Mary", "Eberlein"}; printf("Hey %s\n", me.last);
45
Designated Initializers (C99)
typedef struct name { char first[20]; char last[20]; } fullName; Value can be labeled with the field name: fullName person = {.last = "Presley", .first = "Elvis"}; If field omitted from initializer, set to 0
46
Operations on structs The . access operator has precedence over nearly all other operators Example: typedef struct { int partNum; char partName[30]; int onHand; } part; part part1 = {.partNum = 311, .partName = "usb"}; scanf("%d", &part1.onHand); // . operator higher precedence than & Assigning one struct to another makes a copy: part2 = part1; // copy each field of part1 into part2 Note: structs cannot be compared with == or !=
47
Passing structs Function call: printName(person); Output:
void printName(struct name p) { printf("First name: %s\n", p.first); printf("Last name: %s\n", p.last); } Function call: printName(person); Output: First name: Elvis Last name: Presley Passing a structure to a function or returning a struct both require making a copy of all fields in the structure.
48
struct return values Function call:
struct name makeAName(char *firstName, char* lastName) { struct name elvis; strcpy(elvis.first, firstName); strcpy(elvis.last, lastName); return elvis; } Function call: struct name theKing = makeAName("Elvis", "Presley");
49
Example #include<stdio.h> #include<string.h> typedef struct { char first[20]; char last[20]; } fullName; void printName(fullName p); fullName makeAName(char *firstName, char *lastName); int main() { fullName onePerson = makeAName("Bruce", "Lee"); printName(onePerson); fullName someone = onePerson; printName(someone); } Output: First name: Bruce Last name: Lee Firstname: Bruce
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.