CS320 - C Programming1 C Programming Philip Fees CS320.
-
Upload
myles-prosper-riley -
Category
Documents
-
view
234 -
download
0
Transcript of CS320 - C Programming1 C Programming Philip Fees CS320.
CS320 - C Programming 1
C ProgrammingC Programming
Philip Fees
CS320
CS320 - C Programming 2
Introduction 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 3
Workshop 1 TopicsWorkshop 1 Topics
Comments Expressions Grouping symbols Identifiers Loops Conditional branching File I/O Basics
CS320 - C Programming 4
CommentsComments
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 5
ExpressionsExpressions
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 6
Grouping SymbolsGrouping 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 7
IdentifiersIdentifiers
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 8
While LoopWhile Loop
Top testing loop Syntax:
while ( expression )
action
Example:int x = 0;
while ( x < 10 )
x = x + 1;
CS320 - C Programming 9
Do LoopDo Loop
Bottom testing loop Syntax:
do action
while ( expression );
Example:int x = 0;
do {
x = x + 1;
} while (x < 10);
CS320 - C Programming 10
If StatementIf Statement
Conditional Branch Syntax:
if ( expression )
action
Example:if ( x < 10 ) {
printf(“x is less than 10\n”);
}
CS320 - C Programming 11
Else StatementElse 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 12
Nested If Else StatementsNested 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 13
File I/O BasicsFile 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 14
Workshop 2 TopicsWorkshop 2 Topics
data types operators for loop
CS320 - C Programming 15
Data TypesData Types
char short int a.k.a. short int long int a.k.a. long signed, unsigned
CS320 - C Programming 16
Data Types (cont.)Data Types (cont.)
float double long double
CS320 - C Programming 17
Arithmetic OperatorsArithmetic Operators
+ addition, - subtraction, * multiplication, / division, % modulus
-=, *=, /=, %= precedence (left to right): *, /, %, +, - (right to left): %=, +=, -=, *=, /=
CS320 - C Programming 18
Relation/Logic OperatorsRelation/Logic Operators
== equal, != not equal, > greater than, >= greater than/equal, < less than, <= less than/equal
Precedence (left to right): <, <=, >, >=, ==, !=
CS320 - C Programming 19
For LoopFor 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 20
Unary OperatorsUnary 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 21
Workshop 3 TopicsWorkshop 3 Topics
Debugging techniques Print debugging Debuggers Other tools
– run time profilers– performance profilers
CS320 - C Programming 22
print debuggingprint 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 23
Print Debug Example 1Print 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 24
Print Debug Example 2Print 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 25
DebuggersDebuggers
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 26
Basic Debugger FeaturesBasic 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 27
Adv. Debugger FeaturesAdv. Debugger Features
Attach to running process Command history and aliases Memory profiling Code patching Expression evaluation Handling threaded applications Function execution
CS320 - C Programming 28
Run Time ProfilersRun 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 variableschar str[5]; printf(“str=%s\n”,str);
Memory usage stats.
CS320 - C Programming 29
Performance ProfilersPerformance 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 30
Workshop 4 TopicsWorkshop 4 Topics
Branch statements Switch goto Casting Character I/O Bit operators formatted printing using printf
CS320 - C Programming 31
Branch StatementsBranch Statements
break statement - from innermost loopint 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 32
Branch Statements (cont.)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 33
Switch StatementSwitch Statement
Restricted version of if, else if, …, else case values must be constant integer values
switch ( integer expression ) {case constant integer 1:
statement 1case constant integer 2:
statement 2…case constant integer n:
statement 3default: /* optional, but typically a good
practice */default statement
}
CS320 - C Programming 34
Switch ExampleSwitch Example
Example: “fall through case” and breakswitch ( gender ) {case ‘M’:case ‘m’:
printf(“male”);break;
case ‘F’:case ‘f’:
printf(“female”);break;
default:printf(“Pat”);break;
}
CS320 - C Programming 35
goto Statementgoto 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 36
goto Examplegoto 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 37
Conditional ExpressionConditional Expression
ternary operatorexpression1 ? 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 38
Cast OperatorCast 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 39
sizeof Operatorsizeof 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 40
Bitwise OperatorsBitwise 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 41
getchar and putchargetchar 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 42
Formatted PrintingFormatted 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 43
Formatted Printing (cont.)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 44
Formatted Printing (cont.)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 45
Formatted Printing (cont.)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 46
Formatted Printing (cont.)Formatted Printing (cont.)
Some basic examples:1) printf(“%s\n”,”Hello World!”);
2) printf(“%s\t\t%s\n”,”Hello”,”World!”);
3) printf(“Hello World %d!\n”,6);
4) int i1 = 5; double d1 = 6.78; printf(“i1=%d, d1=%lf\n”,i1,d1);
CS320 - C Programming 47
Formatted Printing (cont.)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 48
Formatted Printing (cont.)Formatted Printing (cont.)
Some string examples (from K&R C):char *str = “Hello, World”; /* 12 bytes long */
1) printf(“[%10s]”,str); /* [Hello, World] */
2) printf(“[%-10s]”,str); /* [Hello, World] */
3) printf(“[%20s]”,str); /* [ Hello, World] */
4) printf(“[%-20s]”,str); /* [Hello, World ] */
5) printf(“[%20.10s]”,str); /* [ Hello, Wor] */
6) printf(“[%-20.10s]”,str); /* [Hello, Wor ] */
7) printf(“[%.10s]”,str); /* [Hello, Wor] */
CS320 - C Programming 49
Workshop 5 TopicsWorkshop 5 Topics
functions scope preprocessor varargs
CS320 - C Programming 50
FunctionsFunctions
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 51
C Function DefinitionC 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 52
C Function DeclarationC 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 53
C Functions (cont.)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 54
Call by ValueCall 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 55
Local VariablesLocal 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 56
C PreprocessorC 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 57
Preprocessor DirectivesPreprocessor Directives
Number sign (#) in first column Most often used directives
– #include– #define– #ifdef, #ifndef, #elif, #else, #endif
CS320 - C Programming 58
Including Header FilesIncluding 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 59
Defining ConstantsDefining 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 360if (months > MAX_MONTHS)
CS320 - C Programming 60
Conditional DirectivesConditional Directives
Like if, else if, else Example:
#ifdef SUN#define HOST “SUN Solaris”#else#define HOST “Not SUN Solaris”#endif
cc … -D SUN … <== Unix cc … /D SUN … <== Windows
CS320 - C Programming 61
Avoiding Multiple #includeAvoiding Multiple #include
Nesting of #include’s within #includes could be problematic
Example:myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
…
#endif
CS320 - C Programming 62
Macros vs. FunctionsMacros 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 63
RecursionRecursion
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 64
Recursion AlgorithmRecursion 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 65
Recursion Algorithm (cont.)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 66
Varargs FunctionsVarargs 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 67
Workshop 6 TopicsWorkshop 6 Topics
arrays string library
CS320 - C Programming 68
ArraysArrays
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; /* error */
temp = ages[1];
CS320 - C Programming 69
Arrays (cont.)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 70
Array InitializationArray 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 71
Arrays and PointersArrays 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 72
Arrays and Pointers (cont.)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 73
sizeof Operatorsizeof 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 74
StringsStrings
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 75
Strings and I/OStrings 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 76
Arrays as Function ArgsArrays 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 77
String LibraryString 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 78
String Library - strcatString 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 79
String Library - strcmpString 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); /* ret == 0 */
CS320 - C Programming 80
String Library - strcpyString 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 81
String Library (cont.)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 82
Multidimensional ArrayMultidimensional 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 83
Workshop 7 TopicsWorkshop 7 Topics
pointers pointers and arrays pointer arithmetic command line arguments pointers to functions
CS320 - C Programming 84
PointersPointers
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 85
Declaring PointersDeclaring Pointers
Declaring a pointerint *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 86
Putting it togetherPutting 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 /* is true */
*ptr = 99; /* assigns 99 to int pointed to by ptr */
CS320 - C Programming 87
MiscellaneousMiscellaneous
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 88
Pointer to PointerPointer to Pointer
Pointers can refer to other pointersint 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 89
Pointers and ArraysPointers 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 90
Pointer InitializationPointer 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 91
Pointer Initialization (cont.)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 92
Pointer ArithmeticPointer 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 93
Pointer Arguments to Pointer Arguments to FunctionsFunctions
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 94
Pointer Arguments to Pointer Arguments to Functions (cont.)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 95
Command Line ArgumentsCommand 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 96
Pointers to FunctionsPointers 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 pointerint (*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 97
Pointers to Functions (cont.)Pointers to Functions (cont.)
Examples:int *pFunc(int, char, char *);/* with out parenthesis pFunc is a function that returnsa 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 98
Workshop 8 TopicsWorkshop 8 Topics
Storage classes Type qualifiers
CS320 - C Programming 99
Storage ClassesStorage 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 100
auto Storage Classauto 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 101
extern Storage Classextern 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 102
static Storage Classstatic 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 103
register Storage Classregister 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 104
Storage Class - Multiple Storage Class - Multiple Source FilesSource 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 105
Storage Class - Multiple Storage Class - Multiple Source Files (cont.)Source Files (cont.)
Example (cont.):----------- myfunc.c --------
extern int count;
myfunc() {
count++;
}
CS320 - C Programming 106
Storage Classes for FunctionsStorage 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 107
Type QualifiersType 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 108
const and pointersconst and pointers
const char *ptr - what ptr points at cannot be changed
*ptr = ‘z’; /* compile error */
ptr = “hello”; /* ok */
char * const ptr - what ptr cannot be changed
*ptr = ‘z’; /* ok */
ptr = “hello”; /* compile error */
Explain arguments to strcmp, strcpy, strlen
CS320 - C Programming 109
Workshop 9 TopicsWorkshop 9 Topics
structures typedef unions bit fields enumerated types dynamic memory
CS320 - C Programming 110
StructuresStructures
An aggregate, user defined data type used to represent non-simple, abstract data
Example:struct person {
char name[50];
char dob[11]; /* mm/dd/yyyy */
int height; /* in inches */
int weight; /* in lbs. */
};
struct person aPerson;
CS320 - C Programming 111
Structures (cont.)Structures (cont.)
Array of structuresstruct 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 112
Structures (cont.)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 113
Initializing StructuresInitializing 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 114
Pointers to StructuresPointers 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 115
Nested StructuresNested 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 116
Self-referencing StructuresSelf-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 117
Structures as ArgumentsStructures 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 118
const Structures 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 119
typedeftypedef
User defined datatypes, based on existing data type
Examples:typedef int Years;Years age = 57;
typedef struct person Person;Person bob = {“Bob”, “12/05/1974”, 72, 210};
CS320 - C Programming 120
typedef (cont.)typedef (cont.)
Short hand notation for structure definition:typedef struct {
char name[50];
char dob[11]; /* mm/dd/yyyy */
int height; /* in inches */
int weight; /* in lbs. */
} Person;
Person bob = { … };
CS320 - C Programming 121
UnionUnion
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 122
Bit FieldsBit 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 123
Enumerated TypesEnumerated 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 124
Dynamic MemoryDynamic 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 125
mallocmalloc
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 126
calloccalloc
Typically used to allocate arrays memory is initialized to 0 Example:
char *string = calloc(50,sizeof(char));strcpy(string,”Hello World!”);
CS320 - C Programming 127
freefree
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 128
Linked ListsLinked 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 129
Workshop 10 TopicsWorkshop 10 Topics
I/O
CS320 - C Programming 130
Opening & Closing FilesOpening & 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 131
Character I/OCharacter 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 132
String I/OString 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 133
Character ConversionsCharacter Conversions
#include <ctype.h> toupper(char), tolower(char), isalpha(char),
isdigit(char), isalnum(char), ...
CS320 - C Programming 134
Binary I/OBinary 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 135
Positioning in a FilePositioning 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);