Lecture02 - 0306-381 Applied Programming • C for C...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 0306-381 Applied Programming • C for C++ Programmers, Part II • Advanced C Programming and Data Structures 0306-381 Applied Programming C for C++ Programmers, Part II • Standard Input and Output • printf () • scanf () • File functions Standard Input and Output • C++: Streams – Input: cin – Output: cout • C: Files—attached to text terminal (TTY) – Input: stdin—keyboard – Output: stdout—display – Error output: stderr—display 3 Redirection of Standard I/O • Standard input: stdin – Input redirection specifier: < command parameters < Redirected_Input_File • Standard output: stdout – Output redirection specifier: > command parameters > Redirected_Output_File – Output append redirection specifier: >> command parameters >> Redirected_Output_File • Both standard input and standard output command parameters < Input > Output command parameters < Input >> MoreOutput 4 Input and Output in C • Functions for input: scanf() family (stdio.h) – scanf()—from standard input (file stdin) – fscanf()—from a file – sscanf()—from a string • Functions for output: printf() family (stdio.h) – printf()—to standard output (file stdout) – fprintf()—to a file – sprintf()—to a string 5 C Output with printf() • Function call printf(“Format”, Variables); fprintf(File, “Format”, Variables); – printf (. . .) à fprintf (stdout, . . .) • Variable number of parameters (arguments) – Any number of arguments possible – “Format” specifies number of arguments 6 printf() Format String • Three specifications – Literal text—text characters to be printed exactly as specified – Special text—text characters to be translated and printed – Format text—text characters to specify variables to be printed • Type (integer, float, char, string, etc.) • Format (field size, alignment, padding, etc.) • Enclosed in double quotation marks • Not all specifications required 7 printf() Format String Literal Text • Any “legal” string characters printf (“Here is my text!”); Here is my text! • Some capability lacking – Reserved characters – Formatting • Need special text 8 printf() Format String Special Text • Backslash (“\”) character sequences – Reserved characters – Formatting printf (“Here is my text!\n”); • Common sequences – – – – – – \n: \t: \': \": \\: %%: New line (CR and LF pair) Tab Single quotation mark Double quotation mark Backslash Percent sign 9 printf() Format String Format Text • Percent sign (“%”) character sequences – Variable output specified – Variable value substituted for format text Number = 42; printf (“Here is my number: Here is my number: 42. %d.”,Number); • Common format descriptors – – – – – – – – %d: %u: %c: %s: %f: %x: %X: %p: int; %ld: long int unsigned int; %lu: unsigned long int char char [ ] (i.e., string) double int in hexadecimal, using lowercase letters int in hexadecimal, using uppercase letters pointer in hexadecimal, using lowercase letters 10 printf() Format String Descriptor Format • Format string components – Descriptor—specifies data type of variable – Format —specifies output field • Example formats – %5.2f: double • 5 characters wide (whole + decimal point + decimal) • 2 digits after the decimal point XX.XX – %04X: hex • 4 characters wide • Padded with leading zeroes 11 C Input with scanf() • Function call scanf(“Format”, &Varialbles); fscanf(File, “Format”, &Varialbles); – scanf (. . .) à fscanf (stdin, . . .) • Simpler usage than printf(), in general – scanf() typically used to read a single variable – printf() often used to format and output multiple variables • Addresses of variables = scanf() arguments 12 scanf() Format String • Similar to printf() • Control characters not used • Ignores extraneous input – Fractional numbers for integer or unsigned specifier – White space (e.g., space, tab, and carriage return characters) 13 File functions • Some common functions (stdio.h) – – – – fopen()—open file stream fclose()—close file stream feof()—check for end of file fflush()—flush output buffer stream 14 C File open with fopen() • Format Stream = fopen(“File name”, “File mode”); • File modes – – – – – – r: read text w: write text a: append text rb: read binary wb: write binary ab: write binary 15 0306-381 Applied Programming Advanced C Programming and Data Structures • Dynamic Arrays • Data Structures and Unions • Program Storage Allocation: Function Calls and Returns • Multiple Return Values for Functions Dynamic Memory Allocation • malloc()—Memory allocate void *malloc (unsigned int Bytes); – Returns NULL if unsuccessful – Example: Allocate memory for 20 floats float *Numbers; Numbers = (float *) malloc (20 * sizeof (float)); • free()—Free allocated memory void free (void *Pointer); – Example: Deallocate memory from above free (Numbers); 17 Dynamic array of 100 doubles Dynamic Arrays int Index; /* Index for access */ double *DoubleArray; /* Pointer for array */ double *DoubleArrayTempPtr; /* Temp. Ptr for access */ /* Dynamically allocate array */ DoubleArray = (double *) malloc (100 * sizeof (double)); /* Use array */ /* By array indexing */ DoubleArray [Index] = . . .; . . . = DoubleArray [Index]; /* By pointer */ DoubleArrayTempPtr = DoubleArray; *DoubleArrayTempPtr = . . .; . . . = *DoubleArrayTempPtr; /* Deallocate array */ free (DoubleArray); What if you need to increase the size of a dynamically allocated array? • memcpy() ? • realloc() ? 18 0306-381 Applied Programming Advanced C Programming and Data Structures • Dynamic Arrays FData Structures and Unions • Program Storage Allocation: Function Calls and Returns • Multiple Return Values for Functions 19 struct and union • Structure: data type with several distinct storage fields typedef struct { int X, Y; } RectangularCoordinate; RectangularCoordinate A, B, C, D; /* Point A is (0,0) */ A.X = 0; A.Y = 0; • Union: data type with overlapping storage fields typedef union { int Whole; float Real; } MultiDomain; MultiDomain Argument; /* Argument takes either an integer or a float value */ Argument.Whole = 42; Argument.Real = 27.63; 20 0306-381 Applied Programming Advanced C Programming and Data Structures • Dynamic Arrays • Data Structures and Unions FProgram Storage Allocation: Function Calls and Returns • Multiple Return Values for Functions Portions following D. Scott Wills, ECE, Georgia Institute of Technology. 21 Run-Time Memory Typical Organization Addresses low Code Static data (global variables) Stack (memory for procedures) high Heap (memory for dynamically allocated data) 22 Storage Allocation Strategies • Static allocation – All storage is allocated by the compiler. – No recursion, dynamic memory allocation. • Stack allocation – The run time storage is managed as a stack. – Values of locals can not be retained when an activation ends. – A called activation can not outlive a caller. • Heap allocation – Activation records are allocated/deallocated in any order. – Some form of garbage collection or compaction is needed to reclaim space. 23 Example: Storage Allocation Running Example: int A; (Global or Static) int foo (int x) { int y, z = 5; (Local or Automatic) return (y); } foo: ADD ADDI ADDI SW ADD $30, $29, $0 #FP = SP $29, $29, -8 #Add bytes $1, $0, 5 $1, -8($30) $29, $30, $0 #SP = FP Activation Frame z y SP ToS FP • Dynamically allocated storage associated with a subroutine call • Frame Pointer ($30) ® Activation Frame ToS = Top of stack 24 Organization of Code Area Foo Example: int Foo (int x) { int y, z = 5; return (A); } Bar Example: int Bar () { int M; M = foo (M); } Active Stack Frames Main Foo Bar Foo’ Foo’’ Stack Callee Allocated Caller Allocated z y Return value x Active Frame For Foo 25 Function Calls and Returns • Call sequence of caller – – – – Allocate stack space for actual parameters and return value Put actual parameters onto stack where callee can find them. Save machine state (return address, frame pointer, etc.). Branch to callee. • Call sequence of callee – Allocate stack space for local variables. – Execute function code. • Return sequence of callee – Copy return value to caller-allocated stack space for it. – Deallocate stack space for local variables. • Return sequence of caller – – – – Copy return value, if necessary. Restore machine state (return address, frame pointer, etc.). Deallocate stack space for actual parameters and return value. Continue execution. 26 Example: Procedure Call and Return $30: Frame Pointer—Points to procedure’s frame on stack Running Example: int foo (int x, *y) { int A, B = 7; int C[4]; return (A); } C[3] foo: ADD ADDI ADDI SW LW SW ADD JR $30, $29, $0 $29, $29, -24 $1, $0, 7 $1, -8($30) $1, -4($30) $1, 0($30) $29, $30, $0 $31 SP -24 -20 -16 - 12 7 -8 -4 FP C[2] C[1] C[0] B A (ToS) R.V. y x 27 Example: Multiple Procedure Calls and Returns Running Example: int foo (int x, *y) { return (A); } int bar () { int M, N; M = foo (M, &N); } LW LW LW SW ADD $31, 16($29) $30, 12($29) $1, 0($29) $1, -4($30) $29, $29, 20 bar: ADD $30, $29, $0 ADDI $29, $29, -8 ADDI SW SW LW SW ADDI SW JAL $29, $29, -20 $31, 16($29) $30, 12($29) $1, -4($30) $1, 8($29) $1, $30, -8 $1, 4($29) foo SP Foo FP 0 4 8 12 16 R.V. y &N xM bar’s F.P. bar’s R.A. N M tos -8 -4 FP 28 0306-381 Applied Programming Advanced C Programming and Data Structures • Dynamic Arrays • Data Structures and Unions • Program Storage Allocation: Function Calls and Returns FMultiple Return Values for Functions 29 Multiple Value Functions Example: Rectangular coordinate system • Rectangular coordinate values typedef struct { int X, Y; } RectangularCoordinate; RectangularCoordinate A, B, C, D; • Rectangular coordinate math functions RectangularCoordinate RectCoordAdd (); RectangularCoordinate RectCoordSubt (); • How do these functions interface? 30 • Prototype 1 Multiple Value Function Interfaces RectangularCoordinate RectCoordAdd ( RectangularCoordinate A, Rectangular Coordinate B); • Input: structs • Return: struct • Prototype 2 RectangularCoordinate *RectCoordAdd ( RectangularCoordinate A, Rectangular Coordinate B); • Input: structs • Return: Pointer to struct • Prototype 3 int RectCoordAdd (RectangularCoordinate *Sum, RectangularCoordinate A, Rectangular Coordinate B); • Input: structs • Output: Pointer to struct 31 Interface Prototype 1 Prototype 1: inputs structs; returns struct RectangularCoordinate RectCoordAdd ( RectangularCoordinate A, Rectangular Coordinate B) { /* Allocate struct for result */ RectangularCoordinate Sum; /* Perform rectangular arithmetic */ Sum.X = A.X + B.X; Sum.Y = A.Y + B.Y; /* Return result*/ return Sum; } /* RectCoordAdd */ 32 Interface Prototype 1 Analysis Prototype 1: inputs structs; returns struct RectangularCoordinate RectCoordAdd ( Copy RectangularCoordinate A, Rectangular Coordinate B) { RectangularCoordinate Sum; Sum.X = A.X + B.X; Sum.Y = A.Y + B.Y; return Sum; } /* RectCoordAdd */ Sum.Y Sum.X R.V..Y R.V..X B.Y B.X A.Y A.X F.P. R.A. tos Before/After Call Caller function •Works in all conditions •Advantages –Intuitive implementation –Chaining support Stack Frame D = RectCoordAdd (RectCoordAdd (A, B), C) •Disadvantages –Slow: stack frame result copy 33 Interface Prototype 2 Prototype 2: inputs structs; returns pointer to struct RectangularCoordinate *RectCoordAdd ( RectangularCoordinate A, Rectangular Coordinate B) { /* Allocate struct for result */ RectangularCoordinate Sum; /* Perform rectangular arithmetic */ Sum.X = A.X + B.X; Sum.Y = A.Y + B.Y; /* Return result*/ return &Sum; } /* RectCoordAdd */ 34 Interface Prototype 2 Analysis Prototype 2: inputs structs; returns pointer to struct RectangularCoordinate *RectCoordAdd ( RectangularCoordinate A, Rectangular Coordinate B) { /* Allocate struct for result */ RectangularCoordinate Sum; /* Perform rectangular arithmetic */ Sum.X = A.X + B.X; Sum.Y = A.Y + B.Y; /* Return result*/ return &Sum; } /* RectCoordAdd */ Sum.Y Sum.X R.V. B.Y B.X A.Y A.X F.P. R.A. tos Before/After Call Caller function Sets Pointer •Fails in some conditions •Advantages –Fast –Chaining support? Stack Frame D = *RectCoordAdd (*RectCoordAdd (A, B), C) Pointer reference to deallocated memory after function return •Disadvantages –Not always correct –Chaining requires copy à slow 35 Interface Prototype 3 Prototype 3: inputs structs; outputs pointer to struct int RectCoordAdd (RectangularCoordinate *Sum, RectangularCoordinate A, Rectangular Coordinate B) { /* Perform rectangular arithmetic */ (*Sum.X) = A.X + B.X; (*Sum.Y) = A.Y + B.Y; /* Return result*/ return 0; } /* RectCoordAdd */ 36 Interface Prototype 3 Analysis Prototype 3: inputs structs; outputs pointer to struct int RectCoordAdd (RectangularCoordinate *Sum, RectangularCoordinate A, Rectangular Coordinate B) { /* Perform rectangular arithmetic */ (*Sum.X) = A.X + B.X; (*Sum.Y) = A.Y + B.Y; /* Return result*/ return 0; } /* RectCoordAdd */ R.V. B.Y B.X A.Y A.X &Sum F.P. R.A. tos Before/After Call Caller Modifies Existing struct •Works in all conditions •Advantages –Straight-forward solution –Fast: No result copy Stack Frame •Disadvantages –No chaining support –Need to copy result for dependent calls •Remedy with all pointer parameters •This remedy requires data dependency analysis 37 ...
View Full Document

This note was uploaded on 04/27/2010 for the course EECC 0306-381 taught by Professor Roymelton during the Spring '10 term at RIT.

Ask a homework question - tutors are online