Complex Data Types: Arrays & Structs Topic 7

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
C programming---String. String Literals A string literal is a sequence of characters enclosed within double quotes: “hello world”
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Introduction to C programming
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Topic 21 arrays - part 1 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from "Should.
1-d Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
Strings CSCI 112: Programming in C.
Computer Science 210 Computer Organization
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
Day 02 Introduction to C.
CSE 303 Lecture 14 Strings in C
Module 2 Arrays and strings – example programs.
Computer Science 210 Computer Organization
Arrays in C.
Building Java Programs
Building Java Programs
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Building Java Programs Chapter 7
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Building Java Programs
Building Java Programs
Building Java Programs
EECE.2160 ECE Application Programming
Introduction to C Topics Compilation Using the gcc Compiler
python.reset() Also moving to a more reasonable room (CSE 403)
Chapter 16 Pointers and Arrays
Chapter 8 Character Arrays and Strings
Building Java Programs
Introduction to C Topics Compilation Using the gcc Compiler
Structs Adapted from Dr. Mary Eberlein, UT Austin.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings in C Array of characters is called a string.
Building Java Programs
File output; Arrays reading: 6.4 – 6.5, 7.1
Building Java Programs
Variables in C Topics Naming Variables Declaring Variables
CS31 Discussion 1H Fall18: week 6
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
Presentation transcript:

Complex Data Types: Arrays & Structs Topic 7 Plan for the Day: Array Basics Strings (aka character arrays) Structures

Arrays

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.

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.

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.

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

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

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

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};

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

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]) ?

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.

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);

"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

"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

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) { ...

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

Strings

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.

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"; 0 1 2 3 4 5 6 7 8 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'

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

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

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

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";

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

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

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

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

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

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 3.140000 The remaining string: This is pi

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.

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; }

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

command line arguments

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

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

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

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

structs

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

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");

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.

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) {…}

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);

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

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 !=

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.

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");

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