C Programming Philip Fees CS320 CS320 - C Programming 1 Introduction What made C language popular? What is the future of the C language? Why learn the C language? What does ANSI C mean? CS320 - C Programming 2 Workshop 1 Topics Comments Expressions Grouping symbols Identifiers Loops Conditional branching File I/O Basics CS320 - C Programming 3 Comments English(?) description of program logic Describe what program is doing not how /* this is a comment */ Example: /* increment x until it equals 10 */ int x = 0; while ((x = x + 1) < 10); CS320 - C Programming 4 Expressions Statements that are terminated by a semicolon (;) Evaluation part of loops and conditional branching statements Have a boolean value (0 = false, non-zero = true) CS320 - C Programming 5 Grouping Symbols Way of specifying a set of statements Pascal uses ‘begin’ and ‘end’ C uses { and } symbols Example: if ( x < 10 ) { printf(“An example of grouping statements\n”); printf(“x is less than 10\n”); } CS320 - C Programming 6 Identifiers Names of variables and functions [A-Za-z_][A-Za-z0-9_]* Examples: get_next, count, setCount, i Review exercises on page 40 CS320 - C Programming 7 While Loop Top testing loop Syntax: while ( expression ) action Example: int x = 0; while ( x < 10 ) x = x + 1; CS320 - C Programming 8 Do Loop Bottom testing loop Syntax: do action while ( expression ); Example: int x = 0; do { x = x + 1; } while (x < 10); CS320 - C Programming 9 If Statement Conditional Branch Syntax: if ( expression ) action Example: if ( x < 10 ) { printf(“x is less than 10\n”); } CS320 - C Programming 10 Else Statement Optional branch of an if statement Syntax: if ( expression ) action1 else action2 Example: if (x > 10) printf(“x is greater than 10\n”); else printf(“x is less than or equal to 10\n”); CS320 - C Programming 11 Nested If Else Statements Not part of language - readability issue Syntax: if ( expression1 ) action1 else if ( expresion2 ) action2 else if ( expresionN ) actionN else actionN+1 CS320 - C Programming 12 File I/O Basics Include stdio.h, open file, read/write, and close Example: #include <stdio.h> FILE *fp = fopen(“file”,”r”); int amount; fscanf(fp,”%d”,&amount); fclose(fp); CS320 - C Programming 13 Workshop 2 Topics data types operators for loop CS320 - C Programming 14 Data Types char short int a.k.a. short int long int a.k.a. long signed, unsigned CS320 - C Programming 15 Data Types (cont.) float double long double CS320 - C Programming 16 Arithmetic Operators + addition, - subtraction, * multiplication, / division, % modulus -=, *=, /=, %= precedence (left to right): *, /, %, +, (right to left): %=, +=, -=, *=, /= CS320 - C Programming 17 Relation/Logic Operators == equal, != not equal, > greater than, >= greater than/equal, < less than, <= less than/equal Precedence (left to right): <, <=, >, >=, ==, != CS320 - C Programming 18 For Loop Top testing loop Syntax: for ( expression1; expression2; expression3) action Example: int x; for ( x = 0; x < 10; x = x + 1 ) printf(“%d\n”,x); CS320 - C Programming 19 Unary Operators ++ and -- (both prefix and postfix) Increment (decrement) variable by one unit Example: int x=1; printf(“++x = %d, x++ = %d\n”,++x,x++); CS320 - C Programming 20 Workshop 3 Topics Debugging techniques Print debugging Debuggers Other tools – run time profilers – performance profilers CS320 - C Programming 21 print debugging Probably the least efficient technique Place printf/fprintf at various points in code Can be enabled/disabled at compile/run time Can be useful in production trouble shooting Can affect some types of bugs Can significantly increase code size CS320 - C Programming 22 Print Debug Example 1 Compile time option: /D MYDEBUG (-D on UNIX) #include <stdio.h> … char str[10]; ... #ifdef MYDEBUG fprintf(stderr,”%d@%s: value of str=[%*.*s]\n”,__LINE__, __FILE__,sizeof(str),sizeof(str),str); #endif CS320 - C Programming 23 Print Debug Example 2 Compile & Run time #include <stdio.h> … int debugLevel = 1; /* set via command line option */ char str[10]; ... #ifdef MYDEBUG if (debugLevel >= 1) fprintf(stderr,”%d@%s: value of str=[%*.*s]\n”, __LINE__,__FILE__,sizeof(str),sizeof(str),str); #endif CS320 - C Programming 24 Debuggers Lets user interact with executing program Usually part of an integrated development environment or as add-on utility Most debuggers support basic set features Difference is in additional features UNIX adb, sdb, dbx, debugger, etc. Windows part of Visual, Borland, etc. Need to keep symbol table (-g UNIX) CS320 - C Programming 25 Basic Debugger Features Set break point Step through program execution Display/watch variables/address contents Modify variables/address contents Step into, over, out of functions Modify process environment Display stack trace CS320 - C Programming 26 Adv. Debugger Features Attach to running process Command history and aliases Memory profiling Code patching Expression evaluation Handling threaded applications Function execution CS320 - C Programming 27 Run Time Profilers Utilities that report information on a process Bounds checking char str[5]; strcpy(str,”123456789”); Memory leak - dynamically allocate memory that is never released Using initialized variables char str[5]; printf(“str=%s\n”,str); Memory usage stats. CS320 - C Programming 28 Performance Profilers Compile time option – UNIX: compile with -p and prof(1) – Windows: see profiling option for environment Link time utilities Reports various bits of information – # of time function call – min., avg., max. times – call tree CS320 - C Programming 29 Workshop 4 Topics Branch statements Switch goto Casting Character I/O Bit operators formatted printing using printf CS320 - C Programming 30 Branch Statements break statement - from innermost loop int strcmp(char str1[], char str2[]) { int idx; /* local index variable */ for (idx = 0; str1[idx] != 0 && str2[idx] != 0; idx++) if (str1[idx] != str2[idx]) break; return str1[idx] - str2[idx]; } CS320 - C Programming 31 Branch Statements (cont.) continue statement - resume execution at loop evaluation char str[50]; int idx, count = 0; /* fixed length records */ while (scanf(“%50c”,str) != EOF) { for (idx = 0; idx < 50; idx++) { if (isspace(str[idx])) { idx = 49; continue; } else if (str[idx] == ‘A’) count++; } } CS320 - C Programming 32 Switch Statement Restricted version of if, else if, …, else case values must be constant integer values switch ( integer expression ) { case constant integer 1: statement 1 case constant integer 2: statement 2 … case constant integer n: statement 3 default: /* optional, but typically a good practice */ default statement } CS320 - C Programming 33 Switch Example Example: “fall through case” and break switch ( gender ) { case ‘M’: case ‘m’: printf(“male”); break; case ‘F’: case ‘f’: printf(“female”); break; default: printf(“Pat”); break; } CS320 - C Programming 34 goto Statement Unconditional transfer to a label Abused and maligned Overuse results in spaghetti code Limited uses include nested loop exit and post processing clean-up Also useful for single exit point from a function best to limit scope to within a function CS320 - C Programming 35 goto Example Typically database access requires post processing clean-up /* allocate cursors and declare query */ if (error) return FAILED; while (!error) { /* fetch first/next record */ if (error) goto cleanup; /* print record */ } cleanup: /* deallocate cursor */ CS320 - C Programming 36 Conditional Expression ternary operator expression1 ? expression2 : expression3 like an if else statement, but has a value (either expression2 or expression3) Example: int x, y, quotent; … quotent = y == 0 ? 0 : x / y; /* avoid divide by 0 CS320 - C Programming 37 Cast Operator Force value to the given data type Use with caution: prone to errors long x = 999999; short y = (short)x; /* what is value of y? */ Example: char str1[10], str2[10]; memcpy((void *)str1,str2,10); CS320 - C Programming 38 sizeof Operator Calculates the number of bytes the operand requires. Example: printf(“sizeof(char)=%d\n”,sizeof(char)); printf(“sizeof(short)=%d\n”,sizeof(short)); printf(“sizeof(int)=%d\n”,sizeof(int)); printf(“sizeof(long)=%d\n”,sizeof(long)); printf(“sizeof(float)=%d\n”,sizeof(float)); printf(“sizeof(double)=%d\n”,sizeof(double)); printf(“sizeof(char *)=%d\n”,sizeof(char *)); char str[15]; printf(“sizeof(str)=%d\n”,sizeof(str)); printf(“sizeof(10)=%d\n”sizeof(10)); CS320 - C Programming 39 Bitwise Operators Bit manipulation operators ~x one’s complement x x & y bit and x and y x | y bit or x and y x ^ y bit exclusive x and y x << y shift x left y bits x >> y shift x right y bits Example: int flags = DEBUG_ON | TRACE_ON; if (flags & DEBUG_ON) ... CS320 - C Programming 40 getchar and putchar getchar - get a single character (as an int) from stdin; return EOF at end of input putchar - put a single character (as an int) to stdout; return character or EOF on error Example: int c; /* why an int ? */ while ((c = getchar()) != EOF) /* hu? */ if (putchar( c ) == EOF) fprintf(stderr,”putchar(%d) failed\n”,c); CS320 - C Programming 41 Formatted Printing #include <stdio.h> printf(const char *format, arg1, … ,argN) fprintf(FILE *, const char *format, arg1,…,argN) All characters are copied to output % sign begins a conversion code CS320 - C Programming 42 Formatted Printing (cont.) Some basic examples: 1) printf(“Hello World!\n”); 2) printf(“Hello\t\tWorld!\n”); 3) printf(“Hello World!\n”); printf(“==== ======\n”); 4) printf(“H\b_e\b_l\b_l\b_o\b_ W\b_o\b_r\b_l\b_d\b_!\b_\n”); CS320 - C Programming 43 Formatted Printing (cont.) Conversion Codes – – – – – – Begins with % sign Optional flags Optional positive minimum field width Optional period Optional positive precision Argument code CS320 - C Programming 44 Formatted Printing (cont.) Most commonly used conversion codes are c (char), d (char, short, int), f (float/double), s (string) %c replaced by a single ASCII character %d replaced by decimal notation string %f replaced by real number - m.nnnnnn %s replaced by contents of string CS320 - C Programming 45 Formatted Printing (cont.) Some basic examples: 1) 2) 3) 4) printf(“%s\n”,”Hello World!”); printf(“%s\t\t%s\n”,”Hello”,”World!”); printf(“Hello World %d!\n”,6); int i1 = 5; double d1 = 6.78; printf(“i1=%d, d1=%lf\n”,i1,d1); CS320 - C Programming 46 Formatted Printing (cont.) Some advanced examples: int i1 = 5; double d1 = 6.78, d2 = 1.2345; 1) printf(“$%.2f $%.2f\n”,d1,d2); 2) printf(“%4.1f\n”,d2); 3) printf(“%*.*f\n”,4,1,d2); 4) printf(“%06d\n”,i1); 5) printf(“%-*d\n”,6,i1); CS320 - C Programming 47 Formatted Printing (cont.) Some string examples (from K&R C): char *str = “Hello, World”; 1) printf(“[%10s]”,str); 2) printf(“[%-10s]”,str); 3) printf(“[%20s]”,str); 4) printf(“[%-20s]”,str); 5) printf(“[%20.10s]”,str); 6) printf(“[%-20.10s]”,str); 7) printf(“[%.10s]”,str); /* 12 bytes long */ /* [Hello, World] */ /* [Hello, World] */ /* [ Hello, World] */ /* [Hello, World ] */ /* [ Hello, Wor] */ /* [Hello, Wor ] */ /* [Hello, Wor] */ CS320 - C Programming 48 Workshop 5 Topics functions scope preprocessor varargs CS320 - C Programming 49 Functions A unit of programming logic that should perform a specific task given a set of values and having a resulting value. Terminology – – – – is invoked or called passed arguments receives parameters returns a value CS320 - C Programming 50 C Function Definition function header <return_type> functionName ( <args> ) return_type is the data type return by the functions or void args type and argument pairs passed to the function, void for no arguments function body { actions; return expression_of_type_return_type; } CS320 - C Programming 51 C Function Declaration a.k.a. function prototype Used by the compiler to ensure all calls to the function conform function’s “signature” Same as function definition head Argument names are optional Terminate with a semicolon. functions return int by default CS320 - C Programming 52 C Functions (cont.) All C programs consist of at least one function - main Function declarations cannot be nested Order of argument evaluation is not guaranteed CS320 - C Programming 53 Call by Value Function receives parameters that are copies of the arguments values Prevents side effects - function can’t modify the passed arguments C supports Call by Reference via pointers will be covered later CS320 - C Programming 54 Local Variables Scope of parameters and variables defined with a function limited to the function Example: int idx = 0; int func( int arg) { int idx = 1; arg = arg + idx; return arg; } CS320 - C Programming 55 C Preprocessor Process source file before compiling Principle use is to include header files, macros, and constant definitions #include <stdio.h> #define max(a,b) (a > b ? a : b) #define MAXLENGTH 512 CS320 - C Programming 56 Preprocessor Directives Number sign (#) in first column Most often used directives – #include – #define – #ifdef, #ifndef, #elif, #else, #endif CS320 - C Programming 57 Including Header Files Way to define interface to library functions Example: #include <stdio.h> FILE *fp = fopen(“file”,”r”); int amount; fscanf(fp,”%d”,&amount); fclose(fp); CS320 - C Programming 58 Defining Constants Use in place of “hard coding” constant values in the code Example: int months; scanf(“%d”,&months); if (months > 360) /* error */ Better. Why? #define MAX_MONTHS 360 if (months > MAX_MONTHS) CS320 - C Programming 59 Conditional Directives Like if, else if, else Example: #ifdef SUN #define HOST “SUN Solaris” #else #define HOST “Not SUN Solaris” #endif cc … -D SUN … cc … /D SUN … <== Unix <== Windows CS320 - C Programming 60 Avoiding Multiple #include Nesting of #include’s within #includes could be problematic Example: myheader.h: #ifndef MYHEADER_H #define MYHEADER_H … #endif CS320 - C Programming 61 Macros vs. Functions Macros increase program size for the benefit of speed Macro has no type checking #define mymaco(a) (a = a + 1) Argument side affects can occur #define mymaco(a) (a = a + 1) int idx = 1; jdx = mymacro(idx); Note caution on macros - pp178-178 CS320 - C Programming 62 Recursion Programming concept - function calls itself either directly or indirectly Useful for solving a specific problem domain - problem solved by combining results of subproblem. Can be solved with looping algorithm CS320 - C Programming 63 Recursion Algorithm Need a way of end recursion Binary search - find value in sorted list Begin in middle of list If middle of list search value is > middle value, search upper half of list else search bottom half of list. CS320 - C Programming 64 Recursion Algorithm (cont.) int search(int search_value,int list[], int first, int last) { int middle = first + ((last - first) / 2 ); if (search_value == list[middle]) return search_value; /* found it! */ else if (middle == first) return -1; /* not in list */ else { /* keep searching */ if (search_value > list[middle]) search(search_value,list,middle,last); else search(search_value,list,first,middle); } CS320 - C Programming 65 Varargs Functions Writing function with variable # of args. How to: – – – – – – #include <stdarg.h> function_name(required_args,…); va_list arg_ptr; va_start(arg_ptr,last_required_arg); data_type variable = va_arg(arg_ptr,data_type); va_end(arg_ptr); CS320 - C Programming 66 Workshop 6 Topics arrays string library CS320 - C Programming 67 Arrays A set of contiguous data of the same data type C has zero based arrays Example: int ages[2], temp; ages[0] = 10; ages[1] = 47; ages[2] = 21; temp = ages[1]; /* error */ CS320 - C Programming 68 Arrays (cont.) Good practice to use a constant to define the array’s size Example: #define MAX_AGE 2 int ages[MAX_AGE], idx; for (idx = 0; idx < MAX_AGE; idx++) printf(“ages[%d]=%d\n”,idx,ages[idx]); CS320 - C Programming 69 Array Initialization Examples: #define MAX_AGE 4 example 1) int ages[MAX_AGE] = { 10, 47, 21, 78 }; example 2) int ages[9] = { 10, 47, 21, 78 }; example 3) int ages[] = { 10, 47, 21, 78 }; May need to define the array as static Examples: static int ages[] = { 99, 34, 2, 8, 19, 10 }; CS320 - C Programming 70 Arrays and Pointers A pointer is name for an address in memory. C keeps track of all arrays by a pointer to the first element in the array. It is the program’s responsibility to keep track of the length of the array. The & operator gives the address of a variable. CS320 - C Programming 71 Arrays and Pointers (cont.) Example: #define MAX_AGE 4 int ages[MAX_AGE] = {12, 69, 3, 34 }; int *ptr_to_ages; /* defines an integer pointer */ ptr_to_ages = &ages[0]; ptr_to_ages = ages; /*same as above */ ptr_to_ages = &ages[3]; ages = ptr_to_ages; /* error - ages is a constant pointer */ &ages[1] == ages + 1 /* true */ CS320 - C Programming 72 sizeof Operator sizeof on an array determines the number of bytes in the array #define MAX_AGE 6 int ages[MAX_AGE]; printf(“sizeof(ages) = %d\n”,sizeof(ages)); To get the total memory used by the array use sizeof operator: printf(“ages size = %d\n”,sizeof(ages)); CS320 - C Programming 73 Strings C doesn’t directly support a data type of string Strings are null (‘\0’) terminated arrays of characters Example: char *schoolPtr = “Regis”; char school[6] ; /* Why six ? */ school[0] = ‘R’; school[1] = ‘e’; school[2] = ‘g’; school[3] = ‘i’; school[4] = ‘s’; school[5] = ‘\0’; /* end with null char */ CS320 - C Programming 74 Strings and I/O Must account for null terminator Scanf Example: char school[6]; scanf(“%s”,school); /* input must be <= 5 chars*/ Why didn’t above example have &school? printf Example: char school[6] = “Regis”; printf(“%s”,school); CS320 - C Programming 75 Arrays as Function Args Arrays are passed to function by passing address of first element of array Example: int myfunc1(int array[]); int myfunc2(int *array); int ages[5] = { 1, 5, 37, 18, 19 }; myfunc1(ages); myfunc2(ages); myfunc2(&ages[0]); CS320 - C Programming 76 String Library Set of functions that perform various string manipulations strcat, strncat - concatinate two strings strcmp, strncmp - compare two strings strcpy, strncpy - copy one string to an array strlen - returns length of a string strstr, strchr, strrchr - seach for string or char in a string CS320 - C Programming 77 String Library - strcat include <string.h> strcat Example: char str[20] = “Hello”; strcat(str,” World!”); /* str == “Hello World!” */ strncat Example: char str[20] = “Hello”; strncat(str,” World!”,3); /* str == “Hello Wo” */ CS320 - C Programming 78 String Library - strcmp strcmp/strncmp returns 0 if strings are identical or +/- lexicographical difference strcmp Example: int ret = strcmp(“Hello”,”World”); /* ret < 0 */ strncmp Example: int ret = strncmp(“Hello”,”Help”,3); CS320 - C Programming /* ret == 0 */ 79 String Library - strcpy strcpy Example: char str1[20] = “Hello”, str2[20]; strcpy(str2,str1); /* str2 == “Hello” */ strncpy Example: char str1[20] = “Hello”, str2[20]; strncpy(str2,str1,3); /* str2 == “Hel” */ strncpy may not null terminate target string CS320 - C Programming 80 String Library (cont.) strlen returns integer length of string, not including null character strlen Example: int ret = strlen(“Hello World!”); /* ret == 12 */ strstr, strchr, strrchr CS320 - C Programming 81 Multidimensional Array Indicated by additional set of []. C like Pascal is row major Example: int ages[2][3]; / * 2 rows with 3 columns each */ Initialization: int ages[2][3] = {{ 5, 3, 8}, { 17, 19, 14}}; As function argument: int myfunc(int array[][3]); /* must specify all but first size */ CS320 - C Programming 82 Workshop 7 Topics pointers pointers and arrays pointer arithmetic command line arguments pointers to functions CS320 - C Programming 83 Pointers A pointer is a variable that contains a memory address Typically, a pointer contains the address of a variable Addressing operator (&) calculates the address a its operand. &x /* expression value == address of x */ CS320 - C Programming 84 Declaring Pointers Declaring a pointer int *iPtr; float *fPtr; – iptr is a pointer to an integer – fptr is a pointer to a float – white space between int, *, and pointer name is a matter of style. Watch out for int *ptr1, ptr2; * binds to pointer not data type CS320 - C Programming 85 Putting it together Declaring and initializing pointers: int idx = 100; int *ptr = &idx; OR ptr = &idx; Derefferencing - accessing memory pointed to by a pointer (*) *ptr == 100 *ptr = 99; /* is true */ /* assigns 99 to int pointed to by ptr */ CS320 - C Programming 86 Miscellaneous void * is a known as a void pointer useful when data type of memory is not important: Example memcpy() pg 776-777 Can’t take address of constants and expressions Review example 6.1.5 on pg 312 Review exercises on pg 315 # 1-14 CS320 - C Programming 87 Pointer to Pointer Pointers can refer to other pointers int x = 100; int *iPtr, **pPtr; iPtr = &x; pPtr = &iPtr; Typically only use up to double pointers Necessary for functions that manipulate what a pointer points at. Exercises on pg 320 # 1-11 CS320 - C Programming 88 Pointers and Arrays C refers to arrays as constant pointers Consider: char str1[10]; char *ptr = &str1[0]; str1 = ptr; /* illegal because str1 is a const */ ptr = str1; /* ok - same as ptr = &str1[0] */ char str2[] = “Hello World!”; /* str2 is an array */ ptr = “Hello World!”; /* ptr is a pointer */ CS320 - C Programming 89 Pointer Initialization Pointers refer to a valid address, null, or garbage char *ptr; /* globals and statics initialized to null */ main() { int x = 98; int *iPtr1; /* uninitialized locals contain garbage */ int *iPtr2 = &x; } CS320 - C Programming 90 Pointer Initialization (cont.) Pointers must point to valid address before using. char *ptr; /* ptr is a local variable */ scanf(“%s”,ptr); /* BIG PROBLEM */ TO FIX char array[20]; char *ptr = array; scanf(“%s”,ptr); /* or scanf(“%s”,array); */ WARNING: pg 324 - taking array address CS320 - C Programming 91 Pointer Arithmetic Manipulate pointer through arithmetic operations Example: char array[] = “Hello World!”, *ptr = array; ptr++; /* move pointer to address of ‘e’ */ ptr--; /* move pointer to address of ‘H’ */ *ptr++ = getchar(); /* puts input char over ‘H’, moves ptr to ‘e’ */ Exercises on pg 337 # 1 - 19 CS320 - C Programming 92 Pointer Arguments to Functions Used to simulate call by reference Example 1: int month = 2; func(&month); void func(int *m) { int x = 10; *m = 4; m = &x; } CS320 - C Programming 93 Pointer Arguments to Functions (cont.) Example 2: int month1 = 2; int month2 = 14; int *mPtr = &month1; func(&mPtr); void func(int **m) { *m = &month2; } Exercises on pg 349 # 1-10 CS320 - C Programming 94 Command Line Arguments How a C program receives run time command line arguments. Syntax: main (int argc, char *argv[]) How to parse command line arguments – See getopt() CS320 - C Programming 95 Pointers to Functions C treats function names as a constant pointer function pointer must include functions return type and argument type(s) To declare a function pointer int (*pFunc)(int, char, char *); /* pFunc is a pointer to a function that returns an int and has an int, char, and char pointer as arguments */ CS320 - C Programming 96 Pointers to Functions (cont.) Examples: int *pFunc(int, char, char *); /* with out parenthesis pFunc is a function that returns a pointer to an int … */ To call the function: #include <string.h> int (*pFunc)(const char *, const char *); pFunc = strcmp; int ret = (*pFunc)(“Hello”,”Help”); /* OR */ ret = pFunc(“Hello”,”Help”); See qsort for an example CS320 - C Programming 97 Workshop 8 Topics Storage classes Type qualifiers CS320 - C Programming 98 Storage Classes Determines where the memory is allocated and how long it remains in existance location: data or stack segment existance: process, containing block containing block code bounded by braces {} storage classes: auto, extern, static CS320 - C Programming 99 auto Storage Class Default storage class for variables declared in the body of a function Memory automatically release on exit from control block Example: main() { int age; auto int idx; } CS320 - C Programming 100 extern Storage Class Default storage class for variables defined outside a function body. Memory allocated for the life of process Initialized to zero or initial value. Visable to functions that follow definition Example: int age; main() {...} CS320 - C Programming 101 static Storage Class Memory allocated for the life of the process Initialized to zero or initial value. Visable to containing block Maintains value over invocations Example: myfunc() { static int age; } CS320 - C Programming 102 register Storage Class Compiler recommendation use CPU register otherwise set to auto can only be part of control block cannot determine address of variable Example: myfunc() { register int age; } CS320 - C Programming 103 Storage Class - Multiple Source Files use extern and static to control visability as forward reference and across files Example: ---------- main.c -----------main() { extern int count; } int count; CS320 - C Programming 104 Storage Class - Multiple Source Files (cont.) Example (cont.): ----------- myfunc.c -------extern int count; myfunc() { count++; } CS320 - C Programming 105 Storage Classes for Functions Must be extern or static Default for function is extern static limits visability of function to those functions in the same file that follow definition CS320 - C Programming 106 Type Qualifiers Arrays are passed to function by passing address of first element of array const - cannot be lvalue of an assignment volatile - can be modifed by another process volatile const - can only be modified by another process const-ness can be casted away CS320 - C Programming 107 const and pointers const char *ptr - what ptr points at cannot be changed *ptr = ‘z’; ptr = “hello”; char * const ptr - what ptr cannot be changed *ptr = ‘z’; ptr = “hello”; /* compile error */ /* ok */ /* ok */ /* compile error */ Explain arguments to strcmp, strcpy, strlen CS320 - C Programming 108 Workshop 9 Topics structures typedef unions bit fields enumerated types dynamic memory CS320 - C Programming 109 Structures An aggregate, user defined data type used to represent non-simple, abstract data Example: struct person { char name[50]; char dob[11]; int height; int weight; }; struct person aPerson; /* mm/dd/yyyy */ /* in inches */ /* in lbs. */ CS320 - C Programming 110 Structures (cont.) Array of structures struct person team[20]; Use the ‘.’ operator to reference a structures member printf(“aPerson name = %s\n”,aPerson.name); printf(“aPerson height = %d\n”,aPerson.height); strcpy(aPerson.name,”Skippy”); aPerson.height = 70; strcpy(team[0].name,”Bozo the Clown”); CS320 - C Programming 111 Structures (cont.) Tag is not required, but must include definition struct { char name[50]; char dob[11]; … } aPerson; member name is unique within structure sizeof structure includes sizeof members + boundary alignment CS320 - C Programming 112 Initializing Structures Initialization similar to arrays: struct person aPerson = {“Bozo the Clown”, “11/31/1955”, 170, 72}; struct person team[] = {{“Tom”, “1/3/1985”, 70, 48}, {“Sally”, “12/15/1984”, 65, 49}, …}; Assignment operator (=) and deep vs. shallow copy: struct person anotherPerson; anotherPerson = aPerson; CS320 - C Programming 113 Pointers to Structures Declaring and initializing a pointer to a structure struct person aPerson; struct person *personPtr = & aPerson; (*personPtr).height = 72; /* ok */ personPtr->height = 72; /* typical / preferred */ Points to the address of the first byte of the structure (1st byte of the 1st member) CS320 - C Programming 114 Nested Structures Example: struct address { char street[100]; char city[30]; char state[3]; char zip[10]; }; struct person { char name[50]; ... struct address pAddress; } aPerson; printf(“Person street: %s\n”,aPerson.pAddress.street); CS320 - C Programming 115 Self-referencing Structures Can only include a pointer to itself, tag is required. struct person { char name[50]; ... struct person *heir; } aPerson, theHeir; aPerson.heir = &theHeir; printf(“Person name = %s\n”,aPerson.name); printf(“Person\’s heir\’s name = %s\n”,aPerson.heir->name); CS320 - C Programming 116 Structures as Arguments Entire structure is copied: int func(struct person aPerson); struct person bob; int ret = func(bob); Typically passed by pointer: int func(struct person *aPerson); struct person bob; int ret = func(&bob); CS320 - C Programming 117 const Structures All members are constant Example: const struct person aPerson = { … }; aPerson.name[0] = ‘A’; /* Error */ aPerson.height = 68; /* Error */ What about pointer data members? struct person newHeir; aPerson.heir = &newHeir; aPerson.heir->name[0] = ‘A’; aPerson.heir->height = 72; CS320 - C Programming 118 typedef User defined datatypes, based on existing data type Examples: typedef int Years age = 57; Years; typedef struct person Person; Person bob = {“Bob”, “12/05/1974”, 72, 210}; CS320 - C Programming 119 typedef (cont.) Short hand notation for structure definition: typedef struct { char name[50]; char dob[11]; int height; int weight; } Person; /* mm/dd/yyyy */ /* in inches */ /* in lbs. */ Person bob = { … }; CS320 - C Programming 120 Union Holds a single members data to the exclusion of other members typedef struct { int x, y; int diam; } Circle; typedef struct { int x1, y1, x2, y2; } Line; union shape { Circle c; Line l; }; typedef struct { int type; /* 0 - circle, 1 - line, etc. */ union shape s; } Shape; Shape myshape; myshape.type = 0; myshape.s.x = 0; myshape.s.y = 0; myshape.s.diam = 10; CS320 - C Programming 121 Bit Fields Alternative to bitwise operators Cannot take address of field (member) cannot reference field via pointer Example: typedef struct { unsigned int debug : 1; unsigned int options : 4; unsigned int field3 : 3; } Flags; Flags f; f.debug = 1; CS320 - C Programming 122 Enumerated Types Data type with user specified values. enum shape_kind { Circle, Line, Square, Triangle }; typedef struct { shape_kind type; union shape s; } Shape; Shape myshape; myshape.type = Circle; Optional - specify enum value (default is 0). typedef enum { January = 1, February, ... } Month; CS320 - C Programming 123 Dynamic Memory All variables, const, etc. are allocated by compile, link, load time environment. Dynamic memory is run-time allocated memory Allocated from the heap malloc(), calloc(), and free() in stdlib.h CS320 - C Programming 124 malloc Returns a (void *) to address of allocated memory null is return on failure Request amount of memory in bytes Like auto, memory is not initialized Examples: int *ptr = malloc(sizeof(int)); *ptr = 10; char *string = malloc(sizeof(char) * 50); strcpy(string,”Hello World!”); CS320 - C Programming 125 calloc Typically used to allocate arrays memory is initialized to 0 Example: char *string = calloc(50,sizeof(char)); strcpy(string,”Hello World!”); CS320 - C Programming 126 free Program’s responsibility to keep track of first byte of allocated memory Program’s responsibility to release dynamic memory when memory is no longer needed Example: char *string = malloc(sizeof(char), 50); … free(string); CS320 - C Programming 127 Linked Lists Putting it together: structures and dynamic memory allocation Example pg 579: typedef struct elephant { char name[20]; struct elephant *next; } Elephant; CS320 - C Programming 128 Workshop 10 Topics I/O CS320 - C Programming 129 Opening & Closing Files #include <stdio.h> FILE *fp fp = fopen(“file_name”,mode), null on error modes (“r”, “r+”, etc.) fclose(fp) already open, stdin, stdout, stderr CS320 - C Programming 130 Character I/O Fgetc(FILE *), getc(FILE *), getchar() Fputc(char, FILE *), putc(char, FILE *), putchar(int) Example: FILE *fp = fopen(“myfile.txt”,”w+”); int c; if (fp == NULL) return; /* error opening */ while ((c = getchar()) != EOF) fputc(c,fp); fclose(fp); CS320 - C Programming 131 String I/O Fgets(char *, int, FILE*), gets(char *) Fputs(char *,FILE *), puts(char *) gets and puts remove or add newline char Example: FILE *fp = fopen(“myfile.txt”,”w+”); char buf[512]; if (fp == NULL) return; /* error opening */ while (fgets(buf,sizeof(buf),stdin) != NULL) fputs(buf,fp); fclose(fp); CS320 - C Programming 132 Character Conversions #include <ctype.h> toupper(char), tolower(char), isalpha(char), isdigit(char), isalnum(char), ... CS320 - C Programming 133 Binary I/O Fread(void *, size_t size, size_t count, FILE*), fwrite(const void *, ... read(int fd, char *buf, int size) and write(int fd, char *buf, int size) system calls No formatting of data occurs, data written as is in memory Example: fwrite((void *)stdout, sizeof(FILE), 1, stdout); write(1,(char *)stdout,sizeof(FILE)); CS320 - C Programming 134 Positioning in a File Int fseek(FILE *,long offset,int base), long ftell(FILE *), void rewind(FILE *) base one of (SEEK_SET, SEEK_CUR, SEEK_END) Example: /* read bob record from fp, bob is 10th person in file */ struct person bob; fseek(fp, sizeof(struct person) * 9, SEEK_SET); fread((void *)&bob, sizeof(bob), 1, fp); CS320 - C Programming 135