Quick Note on Memory 198:211 Computer Architecture

Similar documents
211: Computer Architecture Summer 2016

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

Chapter 19 Data Structures -struct -dynamic memory allocation

COMPSCI 210 Part II Data Structure

Chapter 19 Data Structures

Midterm 1 Review. Introduction to Programming in C. General. Turing Machine. Universal Turing Machine

Chapter 16 Pointers and Arrays

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

Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi

Chapter 16 Pointers and Arrays

n Address of a variable in memory n Allows us to indirectly access variables ! Array n A list of values arranged sequentially in memory

211: Computer Architecture Summer 2016

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

CS 2461: Computer Architecture I

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Why do we need Pointers? Call by Value vs. Call by Reference in detail Implementing Arrays Buffer Overflow / The Stack Hack

High Performance Computing in C and C++

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Kurt Schmidt. October 30, 2018

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

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

Arrays and Pointers in C. Alan L. Cox

CSCI 171 Chapter Outlines

Pointers and File Handling

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

CS 11 C track: lecture 5

Dynamic memory allocation (malloc)

Heap Arrays. Steven R. Bagley

High Performance Programming Programming in C part 1

Lecture 03 Bits, Bytes and Data Types

First of all, it is a variable, just like other variables you studied

01:198:211 Computer Architecture Lecture 1

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Data Representation and Storage. Some definitions (in C)

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

In Java we have the keyword null, which is the value of an uninitialized reference type

Basic Types and Formatted I/O

Advanced C Programming Topics

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Heap Arrays and Linked Lists. Steven R. Bagley

Computers Programming Course 5. Iulian Năstac

A Fast Review of C Essentials Part I

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

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

THE FUNDAMENTAL DATA TYPES

Data Representation and Storage

Variables and literals

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Work relative to other classes

PRINCIPLES OF OPERATING SYSTEMS

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

EL2310 Scientific Programming

2009 S2 COMP File Operations

Arrays, Strings, & Pointers

Memory, Arrays & Pointers

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

C for C++ Programmers

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

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

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

today cs3157-fall2002-sklar-lect05 1

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

Should you know scanf and printf?

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

C programming basics T3-1 -

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

CS C Primer. Tyler Szepesi. January 16, 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Procedural programming with C

PROGRAMMAZIONE I A.A. 2017/2018

Fundamental of Programming (C)

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Lectures 5-6: Introduction to C

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Arrays and Memory Management

Understanding Pointers

CS61, Fall 2012 Section 2 Notes

Review Topics. Final Exam Review Slides

CS 61c: Great Ideas in Computer Architecture

Lectures 5-6: Introduction to C

EL2310 Scientific Programming

Intermediate Programming, Spring 2017*

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

Lecture 2: C Programm

Fundamental of Programming (C)

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Fundamentals of Programming

Transcription:

Quick Note on Memory 198:211 Computer Architecture Topics: Pointers Advanced Types I/O Week 3 Fall 2012 We ll get into much more detail on this later in the course Remember Von Neuman Architecture All data is stored in memory Memory is addressable Think of lockers!! Locker number, contents of locker Amount of memory required per data type varies Input Unit! Memory! Unit! Arithmetic and Logic (ALU)! Control! Unit! Output! Unit! Memory Think of memory as a long continuous array Memory allocated based on bytes Has an address and contents associated with that address 1 2 3 4 5 6 7 8 9 10 11 12 13 Memory Memory allocated to variables in bytes int x; double y; char z; short int w; This memory stays allocated for the lifetime of the variable 1 2 3 4 5 6 7 8 9 10 11 12 13 1

Pointers - Introduction Any variable that is declared within a program is assigned to a portion of memory to store it s assigned value. Run time systems maintains a mapping (called a symbol table) that store, for each variable, its assigned location in memory. In C, address of a variable can be access by & operator char char1 = a char char2 = b ; printf ( char1,&char1); VarName! char1! MemLoc! x3100! char2! x3101! value a b c address x3100 x3101 x3102 Pointers - Intro (continued) Since we can talk about memory address, we should be able to assign it to a variable as well! A Pointer is a type of variable that stores the address of another variable in memory Allows us to indirectly access variables in other words, we can talk about its address (or where its stored) rather than its value Pointers in C Pointers in C C lets us talk about and manipulate pointers as variables and in expressions. Declaration int *p; /* p is a pointer to an int */ A pointer in C is usually a pointer to a particular data type: int*, double*, char*, float*, etc. Pointer Operators *p -- returns the value pointed to by p &z -- returns the address of variable z Declaration int date; date=5; /* date is integer with value 5 */ int *p; /* p is a pointer to an integer variable */ p=&date /* value of p is address of date */ Remember p is of type pointer (think address) Remember *p is of type integer (think value) Initialize pointer print (,*p); /*STMT2 prints what? */ *p = date + 1 /* STMT 2 make contents of p same as integer date + 1 */ Address=10 Address=6 Address=2 5 10 a p printf ( format, a, &a, *p, p, &p) 2

Pointer Example Pointer Example int i; int *ptr; int i; int *ptr; store the value 4 into the memory location associated with i i = 4; ptr = &i; *ptr = *ptr + 1; i = 4; ptr = &i; *ptr = *ptr + 1; i! ptr!?!?!?! 4300! 4304! random address! i! ptr! 4!?!?! 4300! 4304! random address! Pointer Example Pointer Example int i; int *ptr; int i; int *ptr; store the result into memory at the address stored in ptr i = 4; ptr = &i; *ptr = *ptr + 1; store the address of i into the memory location associated with ptr i = 4; ptr = &i; *ptr = *ptr + 1; read the contents of memory at the address stored in ptr i! ptr! 4! 4300!?! 4300! 4304! random address! i! ptr! 5! 4300!?! 4300! 4304! random address! 3

Pointer Example #include <stdio.h> main() { int value=5; int * value_ptr; printf ("value %d, memory location %d\n", value, &value); value_ptr= &value; printf (" content of value_ptr %d\n", value_ptr); printf (" value pointed to by value_ptr %d\n", *value_ptr); printf (" address of value_ptr %d\n", &value_ptr); printf (" \n \n"); Pointer Example int i; int *ptr; i = 4; ptr = &i; *ptr = *ptr + 1; i! ptr! What would happen if the last statement was:! ptr = *ptr + 1; *ptr = ptr + 1; ptr = ptr + 1;?! 4300!?! 4300! 4304! random address! Useful Examples for Pointers Consider the following function that's supposed to swap the values of its arguments. void Swap(int firstval, int secondval) { int tempval = firstval; firstval = secondval; secondval = tempval; int fv = 6, sv = 10; Swap(fv, sv); printf( Values: (%d, %d)\n, fv, sv); Recall that functions are pass-by-value Pointers as Arguments Passing a pointer into a function allows the function to read/change memory. void NewSwap(int *firstval, int *secondval) {int tempval; tempval = *firstval; *firstval = *secondval; *secondval = tempval; int fv = 6, sv = 10; NewSwap(&fv, &sv); printf( Values: (%d, %d)\n, fv, sv); 4

Null Pointer Sometimes we want a pointer that points to nothing. In other words, we declare a pointer, but we re not ready to actually point to something yet. int *p; p = NULL; /* p is a null pointer */ NULL is a predefined macro that contains a value that a non-null pointer should never hold. Often, NULL = 0, because Address 0 is not a legal address for most programs on most platforms. Using Arguments for Results Pass address of variable where you want result stored Useful for multiple results Example: return value via pointer return status code as function result This solves the mystery of why & with argument to scanf: scanf("%d ", &datain); read a decimal integer and store in datain Structured data objects Arrays Structured data objects are available as object array [] struct union property enumerated, numbered from 0 names and types of fields names and types of fields but only 1 field can be used at any one time 19 Arrays are defined by specifying an element type and number of elements int vec[100]; char str[30]; float m[10][10]; For array containing N elements, indexes are 0..N-1 Stored as linear arrangement of elements Note: Index starts at 0 and the number in the declaration gives the number of elements. 20 5

Arrays Array elements are accessed using the same syntax as in Java: array[index] Example (iteration over array): int i, sum = 0;... for (i = 0; i < VECSIZE; i++) sum += vec[i]; C does not check whether array index values are sensible (i.e., no bounds checking) vec[-1] or vec[10000] will not generate a compiler warning! if you re lucky, the program crashes with Segmentation fault (core dumped) Arrays C references arrays by the address of their first element array is equivalent to &array[0] can iterate through arrays using pointers as well as indexes: int *v, *last; int sum = 0; last = &vec[vecsize-1]; for (v = vec; v <= last; v++) sum += *v; 21 22 2-D arrays 2-dimensional array int weekends[52][2]; [0][0] [0][1] [1][0] [1][1] [2][0] [2][1] [3][0].... weekends Arrays - example #include <stdio.h> void main(void) { int number[12]; /* 12 cells, one cell per student */ int index, sum = 0; /* Always initialize array before use */ for (index = 0; index < 12; index++) { number[index] = index; /* now, number[index]=index; will cause error:why?*/ for (index = 0; index < 12; index = index + 1) { sum += number[index]; /* sum array elements */ return; weekends[2][1] is same as *(weekends+2*2+1) NOT *weekends+2*2+1 :this is an int! 23 17-Sep-12 Advanced Programming Spring 2002 24 6

Arrays SizeOf C does not remember how large arrays are (i.e., no length attribute) int x[10]; x[10] = 5; may work (for a while) In the block where array A is defined: sizeof A gives the number of bytes in array can compute length via sizeof A /sizeof A[0] When an array is passed as a parameter to a function the size information is not available inside the function array size is typically passed as an additional parameter PrintArray(A, VECSIZE); or as part of a struct (best, object-like) or globally #define VECSIZE 10 17-Sep-12 Advanced Programming Spring 2002 25 sizeof(x) - is a function to determine the amount of storage (in bytes) required to store an object of the type of its operand char char_array[20]; int int_array[20]; sizeof(int) is 4 sizeof(char) is 1 sizeof(char_array) is 20 sizeof(int_array) is 80 Number of elements in int_array sizeof(int_array)/sizeof(int) is 20 Arrays Arrays are declared with a type and a size. Size must be known at compile time. char foo1[20]; // an array of 20 characters Arrays are accessed by referring to their elements using index numbers: foo1[10]; // value stored at the 11th element All arrays indexes start at 0; There is NO checking on array bounds int array[10], i =0; for(i=0; i< 10; i++) array[i] = i for(i=0; i< 15; i++){ printf("%d\t%d\n", i, array[i]); Array Storage Elements of an array are stored sequentially in memory!! char grid[10]; First element (grid[0]) is at lowest address of allocated space.! Knowing the first element is enough to access any element! grid[0] grid[1] grid[2] grid[3] grid[4] grid[5] grid[6] grid[7] grid[8] grid[9] 7

Relationship between Arrays and Pointers An array name is essentially a pointer to the first element in the array. [0] char word[10]; char *cptr; cptr = word; /* points to word[0] */ Difference: Can change the contents of cptr, as in cptr = cptr + 1; (The identifier "word" is not a variable.) be careful Correspondence between Ptr and Array Notation Given the declarations on the previous slide, each line below gives three equivalent expressions: char word[10]; char *cptr; cptr = word; cptr word &word[0] (cptr + n) word + n &word[n] *cptr *word word[0] *(cptr + n) *(word + n) word[n] Passing Arrays as Arguments C passes arrays by reference (actually it s by value) the address of the array (i.e., of the first element) is copied. otherwise, would have to copy each element. main() { int numbers[max_nums]; mean = Average(numbers); This must be a constant, e.g., #define MAX_NUMS 10 int Average(int * inputvalues ) { for (index = 0; index < MAX_NUMS; index++) sum = sum + inputvalues[index]; return (sum / MAX_NUMS); int Average(int inputvalues[], );/* Alternative Prototype */ Common Pitfalls with Arrays in C Overrun array limits There is no checking at run-time or compile-time to see whether reference is within array bounds. int array[10]; int i; for (i = 0; i <= 10; i++) array[i] = 0; Declaration with variable size Size of array must be known at compile time. void SomeFunction(int num_elements) { int temp[num_elements]; 8

Pointer Arithmetic Address calculations depend on size of elements C does size calculations under the covers, depending on the size of item being pointed to: double x[10]; double *y = x; *(y + 3) = 13; allocates 10 doubles, size of 80 bytes char s[10]; char *t = s; *(t + 3) = A ; same as x[3] Aside: void, void * Function that doesn t return anything declared as void No argument is also declared as void Special pointer *void can point to anything #include <stdio.h> extern void *f(void); void *f(void) { printf("the big void\n"); return NULL; int main(void) { f(); How far does each pointer move? 17-Sep-12 Advanced Programming Spring 2002 34 Structures in C A struct is a mechanism for grouping together related data items of different types. Recall that an array groups items of a single type. Example: We want to represent an airborne aircraft: int altitude; int longitude; int latitude; int heading; double airspeed; We can use a struct to group these data together for each plane. Defining a Struct We first need to define a new type for the compiler and tell it what our struct looks like. struct flighttype { int altitude; /* in meters */ int longitude; /* in tenths of degrees */ int latitude; /* in tenths of degrees */ int heading; /* in tenths of degrees */ double airspeed; /* in km/hr */ ; This tells the compiler how big our struct is and how the different data items ( members ) are laid out in memory. But it does not allocate any memory. 9

Declaring and Using a Struct To allocate memory for a struct, we declare a variable using our new data type. struct flighttype plane; Memory is allocated, and we can access individual members of this variable: plane.airspeed = 800.0; plane.altitude = 10000; A struct s members are laid out in the order specified by the definition. plane.altitude plane.longitude plane.latitude plane.heading plane.airspeed Defining and Declaring at Once You can both define and declare a struct at the same time. struct whackjob { int height; /* in meters */ int weight; /* in ounces */ char haircolor; /* B, G, etc*/ double wealth; /* in MillionDollars and cents */ snooki; And you can use the celebrity name to declare other structs. struct whackjob ladygaga; typedef C provides a way to define a data type by giving a new name or alias to a predefined type. Can use any readable name for pre defined type Syntax: typedef <type> <name>; Examples: typedef int Color; typedef struct celebrity; Using typedef This gives us a way to make code more readable by giving application-specific names to types. Color x, y; Celebrity beyonce, madonna; Typical practice: Declare typedef s into a header file, and use type names in the main program. If the definition of Flight changes, you might not need to change the code in your main program file. 10

Array of Structs Can declare an array of structs: Flight planes[100]; Each array element is a struct. To access member of a particular element: planes[34].altitude = 10000; Because the [] and. operators are at the same precedence, and both associate left-to-right, this is the same as: (planes[34]).altitude = 10000; Pointer to Struct We can declare and create a pointer to a struct: Flight *planeptr; planeptr = &planes[34]; To access a member of the struct addressed by a Ptr: (*planeptr).altitude = 10000; Because the. operator has higher precedence than *, this is NOT the same as: *planeptr.altitude = 10000; C provides special syntax for accessing a struct member through a pointer: planeptr->altitude = 10000; Passing Structs as Arguments Unlike an array, a struct is always passed by value into a function. This means the struct members are copied to the function s state and changes inside the function are not reflected in the calling routine s copy. Most of the time, you ll want to pass a pointer to a struct. int Collide(Flight *planea, Flight *planeb) { if (planea->altitude == planeb->altitude) {... else return 0; union Like struct (collection of variables of different types) But only one field can store a value at any given time Memory allocated to the maximum required for any field Once a field is allocated, any previous field if any is erased union exptdata {int approxdata; double precisedata;mydata; 11

Dynamic Allocation Memory partition When a variable is declared, memory is allocated for that variable int i, j; What if we don t a priori how may instances of a variable are needed? E.g., a variable number of integers as many as the user wants to enter. We can t allocate an array of integers, because we don t know the maximum number of that might be required. Even if we do know the maximum number, it might be wasteful to allocate that much memory because most of the time only a few integers may be needed. Solution: Allocate storage for data dynamically, as needed. Stack Local variables on stack; grows and shrinks based on calls dynamic Heap Global variables, static constants Dynamic (malloc) Stack Heap Text 45 46 Enter Dynamic Memory Memory allocated from the stack has a limited life-time.! What do we do if we want memory that exists outside the life-time of functions! Two ways to get memory! Declare a variable - gets placed on the stack! Ask the run-time system for a chunk of memory! Requests for dynamic chunks of memory performed using a call to the underlying runtime system (a system call).! Command: malloc and free! Dynamic Memory or heap Dynamic request for memory are honored from heap. Memory Management taken care of by the run-time system. Complicated While functions are being called and returning, activations records are being added and removed from the heap. This does NOT effect the heap. Once allocated it will stay there until freed Question to ask: why do they grow from different directions? 0x0000 instructions global data Stack run-time heap 47 0xFFFF 48 12

malloc The Standard C Library provides a function for allocating memory at run-time: malloc. void *malloc(int numbytes); It returns a generic pointer (void*) to a contiguous region of memory of the requested size (in bytes). The bytes are allocated from a region in memory called the heap. The run-time system keeps track of chunks of memory from the heap that have been allocated. Example 1 #include <stdio.h> #include <malloc.h> main(){ int *base; int i,j; int cnt=0; int sum=0; printf("how many integers you have to store \n"); scanf("%d",&cnt); /* how many integers? */ base = (int *)malloc(cnt * sizeof(int)); if(!base) printf("unable to allocate size \n"); else { for(j=0;j<cnt;j++) *(base+j)=5; 49 50 Using malloc To use malloc, we need to know how many bytes to allocate. The sizeof operator is used to calculate the size of a particular type. planes = malloc(n * sizeof(flight)); We also need to change the type of the return value to the proper kind of pointer this is called casting. planes = (Flight *) malloc(n* sizeof(flight)); 51 Example 2 int airborneplanes; Flight *planes; printf( How many planes are in the air? ); scanf( %d, &airborneplanes); planes = (Flight*) malloc(sizeof(flight) * airborneplanes); if (planes == NULL) { fprintf(stderr, Error in allocating the data array.\n );... planes[0].altitude =... If allocation fails, malloc returns NULL. Note: Can use array notation or pointer notation. 52 13

free Once the data is no longer needed, it should be released back into the heap for later use. Command Line Arguments You can use the command line to provide input to your programs. This is done using the free function, passing it the same address that was returned by malloc. void free(void*); free(base); /* in example 1 */ If allocated data is not freed, the program might run out of heap memory and will be unable to continue. 53 int main( int argc, char * argv [] ){ argc - the number of arguments (including program name) argv pointer to array of char arrays (strings) 54 Command Line (example) Array of strings and double pointers int main(int argc, char * argv []){ int i; printf( %d arguments\n, argc); for(i=0; i<argc; i++) printf( \t%d: %s\n, i, argv[i]); return 0; **argv is a double pointer argv (array name) is a pointer to first element of the array Which in turn is a pointer to char argv[0], argv[1],. argv 55 56 14

File I/O example For our purposes, a file is a sequence of ASCII characters stored on some device. Allows us to process large amounts of data without having to type it in each time or read it all on the screen as it scrolls by. Each file is associated with a stream. May be input stream or output stream (or both!). The type of a stream is a "file pointer", declared as: FILE *infile; #include<stdio.h> void main(){ FILE *fp; fp = fopen( PA1.ANS", w"); fprintf(fp,"%s %d\n", OBAMA",44); fclose(fp) ; The FILE type is defined in <stdio.h>. 57 58 fopen The fopen (pronounced "eff-open") function associates a physical file with a stream. FILE *fopen(char* name, char* mode); First argument: name The name of the physical file, or how to locate it on the storage device. This may be dependent on the underlying operating system. Second argument: mode How the file will be used: "r" -- read from the file "w" -- write, starting at the beginning of the file "a" -- write, starting at the end of the file (append) fprintf and fscanf Once a file is opened, it can be read or written using fscanf() and fprintf(), respectively. These are just like scanf() and printf(), except an additional argument specifies a file pointer. FILE * fpout; fpin; fpout = fopen( PA1.out, w ); fprintf(fpout, "The answer is %d\n", x); fpin = fopen( PA1.in, r ); fscanf(fpin, "%s %d/%d/%d %lf\n", name, &bmonth, &bday, &byear, &gpa); 59 60 15

A String is an Array of Characters I/O with Strings Allocate space for a string just like any other array: char outputstring[16]; Space for string must contain room for terminating zero (i.e. \0 ) Special syntax for initializing a string: char outputstring[16] = "Result = "; which is the same as: outputstring[0] = 'R'; outputstring[1] = 'e'; outputstring[2] = 's';... 61 printf and scanf use "%s" format character for string printf -- print characters up to terminating zero printf("%s", outputstring); scanf -- read characters until whitespace, store result in string, and terminate with zero scanf("%s", inputstring); char outputstring[16] = "Result ="; printf("length: %d\n", strlen(outputstring)); printf("length: %d\n", sizeof(outputstring)); 62 Useful functions for Strings Standard C Library Useful string related functions in string.h char * strcpy(ct, cs) Copy string cs to ct char * ct, cs int strcmp(str1, str2)compare string str1 to str2 char * str1, str2 A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite. size_t strlen(ls) Returns length of ls char * ls 63 I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented by any ANSI standard implementation. Automatically linked with every executable. Implementation depends on processor, operating system, etc., but interface is standard. Since they are not part of the language, compiler must be told about function interfaces. Standard header files are provided, which contain declarations of functions, variables, etc. 64 16

Basic I/O Functions The standard I/O functions are declared in the <stdio.h> header file. Function Description putchar Displays an ASCII character to the screen. getchar Reads an ASCII character from the keyboard. printf Displays a formatted string, scanf Reads a formatted string. fopen Open/create a file for I/O. fprintf Writes a formatted string to a file. fscanf Reads a formatted string from a file. 65 Formatted I/O printf and scanf allow conversion between ASCII representations and internal data types. Format string contains text to be read/written, and formatting characters that describe how data is to be read/ written. %d signed decimal integer %f signed decimal floating-point number %x unsigned hexadecimal number %c ASCII character %s ASCII string 66 Special Character Literals Certain characters cannot be easily represented by a single keystroke, because they correspond to whitespace (newline, tab, backspace,...) are used as delimiters for other literals (quote, double quote,...) These are represented by the following sequences: \n newline \t tab \b backspace \\ backslash \' single quote \" double quote \0nnn ASCII code nnn (in octal) \xnnn ASCII code nnn (in hex) 67 printf Prints its first argument (format string) to stdout with all formatting characters replaced by the ASCII representation of the corresponding data argument. int a = 100; int b = 65; char c = 'z'; char banner[10] = "Hola!"; double pi = 3.14159; printf("the variable 'a' decimal: %d\n", a); printf("the variable 'a' hex: %x\n", a); printf("'a' plus 'b' as character: %c\n", a+b); printf("a char %c.\t A string %s\n A float %f\n", c, banner, pi); 68 17

scanf Reads ASCII characters from stdin, matching characters to its first argument (format string), converting character sequences according to any formatting characters, and storing the converted values to the addresses specified by its data pointer arguments. char name[100]; int bmonth, bday, byear; double gpa; scanf("%s %d/%d/%d %lf", name, &bmonth, &bday, &byear, &gpa); scanf Conversion For each data conversion, scanf will skip whitespace characters and then read ASCII characters until it encounters the first character that should NOT be included in the converted value. %d Reads until first non-digit. %x Reads until first non-digit (in hex). %s Reads until first whitespace character. Literals in format string must match literals in the input stream. Data arguments must be pointers, because scanf stores the converted value to that memory address. 69 70 scanf Return Value Bad scanf Arguments The scanf function returns an integer, which indicates the number of successful conversions performed. This lets the program check whether the input stream was in the proper format. Example: int rv = scanf("%s %d/%d/%d %lf", &name, &bmonth, &bday, &byear, &gpa); Input Stream Return Value Mudd 02/16/69 3.02 5 Muss 02 16 69 3.02 2 Doesn't match literal '/', so scanf quits Two problems with scanf data arguments 1. Not a pointer int n = 0; scanf("%d", n); Will use the value of the argument as an address. 2. Missing data argument scanf("%d"); Will get address from stack, where it expects to find first data argument. If you're lucky, program will crash because of trying to modify a restricted memory location (e.g., location 0). Otherwise, your program will just modify an arbitrary memory location, which can cause very unpredictable behavior. after second conversion. 71 72 18