Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Similar documents
211: Computer Architecture Summer 2016

Standard File Pointers

Fundamentals of Programming. Lecture 11: C Characters and Strings

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C mini reference. 5 Binary numbers 12

Introduction to string

COMP1917: 09 Arrays and Strings

C programming basics T3-1 -

today cs3157-fall2002-sklar-lect05 1

C: How to Program. Week /May/28

Advanced C Programming Topics

Approximately a Test II CPSC 206

Chapter 8 - Characters and Strings

8. Characters, Strings and Files

Chapter 8 C Characters and Strings

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Contents. A Review of C language. Visual C Visual C++ 6.0

File IO and command line input CSE 2451

Arrays, Strings, & Pointers

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

C PROGRAMMING. Characters and Strings File Processing Exercise

Input / Output Functions

Standard C Library Functions

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

C Libraries. Bart Childs Complementary to the text(s)

CS 261 Fall Mike Lam, Professor. Structs and I/O

Strings and Library Functions

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Intermediate Programming, Spring 2017*

Chapter 8: Character & String. In this chapter, you ll learn about;

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Characters and Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C

SWEN-250 Personal SE. Introduction to C

Euclid s algorithm, 133

Lecture 05 Pointers ctd..

Introduction to file management

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Recitation 2/18/2012

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Organization of a file

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

PRINCIPLES OF OPERATING SYSTEMS

Scientific Programming in C V. Strings

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Warm-up sheet: Programming in C

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Strings. Steven R. Bagley

C for C++ Programmers

Lecture 04 Introduction to pointers

Course organization. Course introduction ( Week 1)

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Introduction to C/C++ Lecture 5 - String & its Manipulation

COP 3223 Final Review

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

CSC 2400: Computer Systems. Arrays and Strings in C

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Chapter 9 Strings. With this array declaration: char s[10];

C Language: Review. INFO High Performance Scientific Computing. 26 septembre 2017

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

The Design of C: A Rational Reconstruction (cont.)

UNIT-I Input/ Output functions and other library functions

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

CSCI 171 Chapter Outlines

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Multiple Choice Questions ( 1 mark)

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

CSCI 2132 Final Exam Solutions

Programming Fundamentals

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

CSC 2400: Computer Systems. Arrays and Strings in C

Input/Output Week 5:Lesson 16.1

LECTURE 15. String I/O and cstring library

2009 S2 COMP File Operations

Lecture 03 Bits, Bytes and Data Types

File Handling in C. EECS 2031 Fall October 27, 2014

Array Initialization

Appendix A Developing a C Program on the UNIX system

25.2 Opening and Closing a File

Today s Learning Objectives

CS1003: Intro to CS, Summer 2008

C Programming. Unit 9. Manipulating Strings File Processing.

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

In the case of the dynamic array, the space must be deallocated when the program is finished with it. free(x);

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

File Handling. 21 July 2009 Programming and Data Structure 1

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

LESSON 4. The DATA TYPE char

Transcription:

Strings and Pointers Announcements Lab 4 Why are you taking this course? Lab 5 #, 8: Reading in data from file using fscanf Quiz Quiz Strings Special character arrays End in null character, \ char hi[6]; H i! \ 3 4 5 char hello[]; H e l l o, m y n a m e i s \ Null character--not a space-- marks end of string Initializing Strings char hello[] = { hello{ hello }; Implicitly, the null character is added to the end The length of the array is set to 6 char hi[] = hi ; Null characted appended Length of the array is 3 char greetings[] = { g, r, e, e, t, i, n, g }{ Just a character array, not a string because no null character Character I/O Have to understand how to manipulate characters to manipulate strings scanf scanf( %c,, &); getchar Returns a character from stdin (terminal) Use: char ; = getchar();

Pitfalls in reading in characters Enter ( \n )) triggers getchar or scanf But, \n is a character! Be careful when using scanf scanf( %c %c,, &, &y); scanf looks for the white space character between characters. But, isn t whitespace a character? If you re having trouble with input with newline chars, try adding fflush(stream) Get rid of \n that may still be in input stream Outputting characters printf( %c %c,, char); (or fprintf) putchar(char) Since a character is represented as an integer, can print out integers Get their character representation puts(char), fputs(char) strings.c Integer representation of characters ASCII (integer) values for characters At a low-level, each character is represented by an integer Can actually print out integers as characters using putchar Eample: putchar(35) --> prints # Integer representation allows C to do easier character manipulation and processing E: a and b are apart and a < b See Table 3. for the character/integer representation or ascii_table.c ascii_table.c Formatting Strings in printf String format specifier has a field width Right-justify the string Eample: printf( %4s %4s,, string); Has width of 4 Right-justifies string so that it takes up 4 characters If string is longer than 4 characters, it will look as if you did not specify a field width Assigning to Strings Cannot just assign hello = hi ; Why? hello is actually the address of the first element in the character array char hello[]; H hello e l l o, m y Can t change hello s address in memory n a m e i s \ String Functions for Assignments Include string.h Need to copy a string into another one strcpy(char *dst* dst,, char *src* src) char a[]; strcpy(a, new string ); Implicitly ends in a null character a now contains the string new string

String Functions: Determining Size sizeof( ( char_array_name ) Returns amount of memory allocated to the array strlen( ( char_array_name ) Returns length of the string Eample: char eample[] = eample ; sizeof: : Bytes strlen: : Why don t we have a similar length function for numeric arrays? String I/O: Input scanf( %s %s,, char_array_name); Don t t need the [] or & when passing the argument, char_array_name Reads in one word (until whitespace) ) from stdin fscanf works similarly gets( char_array_name ); Reads until newline character Stored in char_array_name Newline character is not included in the string Appends a null character to the string Why is gets unsafe? stringio.c String I/O: Input fgets(char_array_name, length, stream) Reads until newline character or length- characters from the input stream, e.g., file stream Stored in char_array_name Newline character is included in the stored string Appends a null character to the string (after the \n) Why is fgets the preferred way to read character input? String Input Functions Summary Name scanf, fscanf gets fgets Notes Reads in one word Reads in one line, does not include newline Reads in one line until some limit, includes newline character stringio..c String I/O: Output printf( %s %s,, char_array_name) Unlike scanf,, prints the whole string, regardless of white space puts(char_array_name) Prints the string out Appends a newline character to output fputs(char_array_name, outputstream) Prints out the string String Output Functions Summary Name printf, fprintf puts fputs Notes Prints whole string Prints string, appends newline Prints string to stream 3

Manipulating Characters Character Functions: Table. in Book Handle tetual input Determine character type isalnum: : alpha-numeric character isalpha: : alphabetic character iscntrl: : control character (like newline,, tab) Manipulating Characters tolower Return the lowercase version of the character Could we implement this function? toupper Return the uppercase version of the character More string functions Common string functions: Table.3 atoi: : returns the int value of a string strcat: : combine two strings into one string strcmp: : compares two strings Use to sort strings (using algorithms from last week) Lots more! -D Character Arrays Similar to -D numeric arrays Eample, a dictionary /* words, at most 39 characters long (plus the null character) */ char dictionary[][4]; dictionary[] is cat,, which is a char[] dictionary[][] is t,, which is a char boy 99 cat dog zebra -D Character Arrays How would you print each word? for(i=; i < ; i++) printf( %s %s,, dictionary[i]); How would you print the second character in each word? for(i=; i < ; i++) printf( %c %c,, dictionary[i][]); Pointers Points to a location in memory int = ; int *=&; Means that is of type pointer to an int. is stored in first available memory location, points to the location of New Operators: &: address of *: value of (or dereferencing) Memory Location 4 8 9996 Value pointere.c 4

Pointers Points to a location in memory int = ; int *=&; To get the value of, use * Print a memory location: %p To assign to outside of an initialization: = &; Memory Location 4 8 9996 Value Pointers Points to a location in memory int = ; int *=&; What happens if we * = 8; Memory Location 4 8 9996 Value 8 pointere..c Pointers Points to a location in memory int = ; int *=&; What happens if we = 9; Memory Location 4 8 9996 Value 9 pointere..c Using pointers Besides initialization to point to an address, most uses of pointers will have the star (*) before the variable Usually, want the value of the pointer, not the address Eamples: Assignment: ** = value; Use: = ** + * Assignment/Use: ** = * + But you have to be careful with precedence! pointere.3.c Using pointers Never use & on LHS of assignment Can t t change the memory address How would you know if a memory location is available? & can be used with any use (not definition) of a variable variable s s address is always valid * can only be used with pointer variables Otherwise, will look up values at weird memory locations (e.g., memory location ). Using pointers: data types int ; int * = &; int *Ptr = && ; ; /* a pointer to an int pointer */ Variable Ptr & Type int int* int** int* Trend? & -> adds a * to the data type Pointers can be used with any data type pointere.4.c 5

We have been using pointers! Array identifiers are pointers to the first element in the array int grades[]; grades 6 In scanf,, we had to use &var notation So we could modify the value in var Now, you know why the ampersand! 96 5 85 9 6 88 9 83 Pointers and Functions Instead of pass-by-value, we can pass-by- reference We discussed pass-by-ref briefly last week Using pointers allows us to modify the parameters passed in (also called reference parameters) Eample: swapping numbers Recall that before, our swap function did not change the variables after returning to the main function swap.*.c Pointers and Functions Two different functions to square a number int square( int n ); void square( int *n ); Pass By Reference Allows us to return more than one variable from a function Can change values in multiple variables Passing arrays is pass by reference Because arrays are pointers Why we could modify arrays square..c Arrays passed to functions The following two function prototypes are equivalent: void modarray( int array[] ); void modarray( int *array ); Strings as character pointers Since arrays and pointers are equivalent string == character array == character pointer However, once you ve chosen either the array or pointer, must be consistent in use in function headers and passing parameters Why would we choose one representation over another? Character arrays have an associated length May not want to deal with a fied length 6

Command-line Arguments Pass the program arguments through the command-line E: cp file.c filecopy.c Adds more fleibility to your programs Change program depending on the arguments or even the number of arguments file.c and filecopy.c are command-line arguments to the UNIX command cp Adding command-line arguments to the program Modify the type signature of main() Takes two parameters: int argc,, char *argv* argv[] argc: : the number of arguments (argument count) argv: : the vector of arguments as strings Eample: int main( int argc,, char *argv* argv[] ) argv argc = 3 Names of parameters to main can change but types cannot cp file.c filecopy.c Name of the program First argument Second argument argv: : close up char *argv* argv[] An array of character pointers Why not a fied-length, -d array? What does -d array look like as a parameter? What if an argument is a number? argv: : close up What if an argument is a number? Must convert the string into a number using a string function atof: : convert the value of the string to a float atoi: : convert the value of the string to an integer argv argv argc = 3 cp file.c filecopy.c Quotation marks are not part of the argument. They emphasize that each argument is a string. argc = 3 args.c a.out 3.4 8 Name of the program First argument Second argument args..c Review: Opening the file Either r for read w for write Prototype: FILE *fopen* fopen(char *filename, char *mode); Returns NULL if there was some problem File does not eist, incorrect permissions We ll talk more about Eample usage: char * net week file_ = fopen( data.tt data.tt, r ); Check that file opened if( file_ == NULL ) { printf( File data.tt did not open.\n ); eit(); } How Character Arrays change what we can do with file I/O Passing a variable string

Review: Selection Sort Key idea: keep track of the sorted and unsorted parts of the array Algorithm: While array is not sorted Find the maimum of the unsorted part Swap with element in the highest position in the unsorted part -3 4 5 8 Highest position in unsorted part 9 6 Etend Selection Sort to Strings While array is not sorted Find the maimum of the unsorted part Swap with element in the highest position in the unsorted part What is the maimum? How do we swap? car bat zebra 3 kite 4 lamb 5 ball 6 man fish 8 soap 9 arm Ma in unsorted part stringsort..c 8