5/24/2016

Resources

• Kochen, Programming in , Third Edition

Review of Programming • Brian Kernighan and Dennis Ritchie, The C Programming C Language , 2 nd Edition, Prentice Hall – Is considered “THE” book on C : coauthor belongs to the creators of the C programming language – The book is not an introductory programming manual; it assumes some familiarity with basic programming concepts • C Programming Notes by Steve Summit http://www.eskimo.com/~scs/cclass/notes/top.html

Based on the Original Slides from Politehnica International- Computer Engineering Lecture Slides

Compilers The C Programming Language • Developed by Dennis Ritchie at AT&T Bell Laboratories in the early 1970s Source Machine Compiler Code Code • Growth of C tightly coupled with growth of Unix: Unix was written mostly in C • Success of PCs: need of porting C on MS-DOS • Many providers of C compilers for many different platforms => Input Executable Output need for standardization of the C language data Program data • 1990: ANSI C (American National Standards Institute) • International Standard Organization: ISO/IEC 9899:1990

Compiler: analyzes program and • 1999: standard updated: , or ISO/IEC 9899:1999 translates it into machine language Executable program: can be run independently from compiler as many times => fast execution

1 5/24/2016

The first C program Compiling and running C programs uses standard input and output functions Editor (printf) Source code #include file.c the program int main (void) begin of program { Compiler printf ("Programming is fun.\n"); Object code statements return 0; file.obj end of program }

Libraries main: a special name that indicates where the program must begin execution. It is Linker a special function . Executable code file.exe first statement: calls a routine named printf, with argument the string of characters IDE (Integrated “Programming is fun \n” Development last statement: finishes execution of main and return to the system a status value Environment) of 0 (conventional value for OK)

C Compilers and IDE’s Debugging program errors • One can: – use a text editor to edit source code, and then use independent Editor command-line compilers and linkers Syntactic Source code Errors – use an IDE: everything together + facilities to debug, develop and file.c organize large projects • There are several C compilers and IDE’s that support various C compilers Compiler We will use and the “GCC” compiler. Object code • file.obj gcc prog.c  porg.out

Libraries Linker Executable code file.exe

Semantic Errors

2 5/24/2016

Displaying multiple values Using comments in a program

/* This program adds two integer values and displays the results */ #include int main (void) #include { int main (void) int value1, value2, sum; { value1 = 50; // Declare variables value2 = 25; int value1, value2, sum; sum = value1 + value2; // Assign values and calculate their sum printf ("The sum of %i and %i is %i\n",value1, value2, sum); value1 = 50; return 0; value2 = 25; } sum = value1 + value2; // Display the result printf ("The sum of %i and %i is %i\n", The format string must contain as many placeholders as expressions to be printed value1, value2, sum); return 0; }

Example: Using data types Basic Data Types - Summary

Type Meaning Constants Ex. printf #include int Integer value; guaranteed to contain at least 16 bits 12, -7, %i,%, %x, int main (void) 0xFFE0, 0177 %o { short int Integer value of reduced precision; guaranteed to - %hi, %hx, int integerVar = 100; contain at least 16 bits %ho float floatingVar = 331.79; long int Integer value of extended precision; guaranteed to 12L, 23l, %li, %lx, 0xffffL %lo double doubleVar = 8.44e+11; contain at least 32 bits char charVar = 'W'; long long Integer value of extraextended precision; guaranteed 12LL, 23ll, %lli, 0xffffLL %llx, %llo printf ("integerVar = %d\n", integerVar); int to contain at least 64 bits printf ("floatingVar = %f\n", floatingVar); unsigned Positive integer value; can store positive values up 12u, 0XFFu %u, %x, %o printf ("doubleVar = %e\n", doubleVar); int to twice as large as an int; guaranteed to contain at printf ("doubleVar = %g\n", doubleVar); least 16 bits (all bits represent the value, no sign bit) printf ("charVar = %c\n", charVar); unsigned - %hu, %hx, return 0; short int %ho } unsigned 12UL, 100ul, %lu, %lx, long int 0xffeeUL %lo

unsigned 12ull, %llu, long long 0xffeeULL %llx, %llo int

3 5/24/2016

Basic Data Types - Summary (contd.) Integer and Floating-Point Conversions

Type Meaning Constants printf // Basic conversions in C #include float Floating-point value; a value that can contain decimal 12.34f, 3.1e- %f, %e, places; guaranteed to contain at least six digits of 5f %g int main (void) precision . { double Extended accuracy floating-point value; guaranteed to 12.34, 3.1e-5, %f, %e, float f1 = 123.125, f2; contain at least 10 digits of precision . %g int i1, i2 = -150; char c = 'a'; long Extraextended accuracy floating-point value; 12.341, 3.1e- %Lf, i1 = f1; // floating to integer conversion double guaranteed to contain at least 10 digits of 5l %Le, %Lg printf ("%f assigned to an int produces %d\n", f1, i1); precision. f1 = i2; // integer to floating conversion char Single character value; on some systems, sign 'a', '\n' %c printf ("%d assigned to a float produces %f\n", i2, f1); extension might occur when used in an expression. f1 = i2 / 100; // integer divided by integer printf ("%d divided by 100 produces %f\n", i2, f1); unsigned Same as char, except ensures that sign extension - char does not occur as a result of integral promotion. f2 = i2 / 100.0; // integer divided by a float printf ("%d divided by 100.0 produces %f\n", i2, f2); signed Same as char, except ensures that sign extension - f2 = (float) i2 / 100; // type cast operator char does occur as a result of integral promotion. printf ("(float) %d divided by 100 produces %f\n", i2, f2); return 0; }

The Type Cast Operator The assignment operators

• f2 = (float) i2 / 100; // type cast operator • The C language permits you to join the arithmetic operators with the • The type cast operator has the effect of converting the value of the variable i2 to assignment operator using the following general format: op=, where op type float for purposes of evaluation of the expression. is an arithmetic operator, including +, –, ×, /, and %. • This operator does NOT permanently affect the value of the variable i2; • op can also be a logical or bit operator => later in this course • The type cast operator has a higher precedence than all the arithmetic operators • Example: except the unary minus and unary plus. count += 10; – Equivalent with: • Examples of the use of the type cast operator: count=count+10; • (int) 29.55 + (int) 21.99 results in 29 + 21 • Example: precedence of op=: (float) 6 / (float) 4 results in 1.5 • a /= b + c • (float) 6 / 4 results in 1.5 – Equivalent with: a = a / (b + c) – addition is performed first because the addition operator has higher precedence than the assignment operator

4 5/24/2016

Program input The while statement

#include It’s polite to while ( expression ) int main (void) display a { message before program statement int n, number, triangularNumber; printf ("What triangular number do you want? "); scanf ("%i", &number); triangularNumber = 0; Reads integer while ( number <= 0 ) { for ( n = 1; n <= number; ++n ) from keyboard printf (“The number must be >0“); triangularNumber += n; printf (“Give a new number: “); printf ("Triangular number %i is %i\n", number, scanf(“%i“, &number); triangularNumber); } return 0; }

Scanf: similar to printf: first argument contains format characters, next arguments tell where to store the values entered at the keyboard More details -> in a later chapter !

Example – do while Statements break and continue • Programming style: don’t abuse break !!! // Program to reverse the digits of a number #include ... int main () { while ( number != 0 ) { int number, right_digit; // Statements to do something in loop printf ("Enter your number.\n"); scanf ("%i", &number); printf("Stop, answer 1: "); do { right_digit = number % 10; scanf ("%i", &answer); printf ("%i", right_digit); if(answer == 1) number = number / 10; } break; // very bad idea to do this while ( number != 0 ); printf ("\n"); } return 0; }

5 5/24/2016

Statements break and continue Example: compound relational test

Continue also not so good style!!! // Program to determine if a year is a leap year ... #include int main (void) while ( number != 0 ) { { // Statements to do something in loop int year, rem_4, rem_100, rem_400; printf(“Skip next statements answer 1: "); printf ("Enter the year to be tested: "); scanf ("%i", &answer); scanf ("%i", &year); if(answer == 1) rem_4 = year % 4; continue; // not so good idea… rem_100 = year % 100; // Statements to do something in loop rem_400 = year % 400; if ( (rem_4 == 0 && rem_100 != 0) || rem_400 == 0 ) // If answer was 1 these statements are printf ("It's a leap year.\n"); // not executed. They are skipped. else // Go straight to the beginning of while printf (“It's not a leap year.\n"); } return 0; }

Logical operators Boolean variables

Operator Symbol Meaning // Program to generate a table of prime numbers AND && X && y is true if BOTH x and y are true #include OR || X || y is true if at least one of x and y is true int main (void) { int p, d; A flag : assumes only NOT ! !x is true if x is false _Bool isPrime; one of two different for ( p = 2; p <= 50; ++p ) { values. The value of a Logical values as operands or in tests: true = non-zero, false=zero isPrime = 1; flag is usually tested in the program to see if it for ( d = 2; d < p; ++d ) Logical values returned as results of expressions: true = 1, false=zero is “on” (TRUE) or “off ” if ( p % d == 0 ) (FALSE) Precedence Example: 5 || 0 is 1 isPrime = 0; if ( isPrime != 0 ) !, ++, --, (type) printf ("%i ", p); *, /, % } Example for operator precedence: Equivalent test: +, - printf ("\n"); a > b && b > c || b > d (more in C-style): <, <=, >, >=, ==, != return 0; Is equivalent to: if (isPrime) && ((a > b) && (b > c)) || (b > d) } || =

6 5/24/2016

The switch statement (cont) The conditional operator

Break can miss ! condition ? expression1 : expression2

Statement list on condition is an expression that is evaluated first. a case can miss If the result of the evaluation of condition is TRUE (nonzero), then expression1 ! switch (operator) is evaluated and the result of the evaluation becomes the result of the operation. { If condition is FALSE (zero), then expression2 is evaluated and its result ... becomes the result of the operation case '*': case 'x': maxValue = ( a > b ) ? a : b; printf ("%.2f\n", value1 * value2); break; Equivalent to: ... } if ( a > b ) maxValue = a; else maxValue = b;

Standard input/output Brief overview - scanf()

• The C language itself does not have any special • scanf(control string, list of arguments) • Control string: contains format characters statements for performing input/output (I/O) – Important: match the number and type of format characters with the number operations; all I/O operations in C must be carried and type of following arguments ! – Format characters: as for printf out through function calls . • Arguments: variable names prefixed with the address operator (&) • These functions are contained in the standard C • Example: library. • scanf(“%i %i”,&x,&y); • #include • Formatted I/O: scanf(), printf() • Character I/O: getchar(), putchar()

7 5/24/2016

How scanf works getchar() and putchar()

• Scanf: searches the input stream for a value to be read, bypasses any leading whitespace characters • The simplest input mechanism is to read one • scanf ("%f %f", &value1, &value2); character at a time from the standard input , with • scanf ("%f%f", &value1, &value2); getchar • In both cases, user can type: 3 5 • To display a character: putchar 3 5 3 5 • The exceptions: in the case of the %c format characters— the next character from the input, no matter what it is, is read • scanf ("%f %c %f", &value1, &op, &value2); 3 + 5 3 + 5 • scanf ("%f%c%f", &value1, &op, &value2); 3+5 Not OK: 3 +5 => op would take the value , character + would remain as input for value2 !

Example: getchar() Terminating keyboard input

Which character as sign of end of input ? #include You need a #include int main(void) { terminating character int main(void) { Buffered input: the int ch; that normally does char ch; characters you type are while ((ch = getchar()) != EOF) not show up in text. while ((ch = getchar()) != '#') collected and stored in a putchar(ch); putchar(ch); buffer. Pressing Enter return 0; return 0; causes the block of } } characters you typed to be made available to your program getchar returns the next input character each time it is called, or EOF when it encounters end of file. EOF is a symbolic constant defined in . (The value is typically -1) Hello ! I am Hello ! I am EOF from the keyboard: Ctrl+Z Joe from #3. Joe from

8 5/24/2016

Exercise: getchar() Arrays - Example

/* Read characters from input over several lines until EOF. Example: Count lines and characters in input */ int values[10]; Declares an array of 10 elements of type int #include Using Symbolic Constants for array size: int main(void) { #define N 10 int c, nl, nc; … nl = 0; int values[N]; nc = 0; while ((c = getchar()) != EOF) { Valid indexes: nc++; values[0]=5; if (c == '\n') values[9]=7; nl++; Invalid indexes: } values[10]=3; printf("Number of lines in input: %d\n", nl); values[-1]=6; printf("Number of characters in input: %d\n", nc); In memory: elements of an array are stored return 1; at consecutive locations }

Arrays - Example Defining a function

#include Using symbolic #include #define N 6 constants for array int main (void) size makes program void printMessage (void) { more general Function { int values[N]; Definition printf ("Programming is fun.\n"); int index; -occurs ONE time for all } for ( index = 0; index < N; ++index ) { -outside other functions printf(“Enter value of element #%i \n”,index); scanf(“%i”, &values[index]); int main (void) } { for ( index = 0; index < N; ++index ) Function printMessage (); printf ("values[%i] = %i\n", index, values[index]); calls (invocations) printMessage (); return 0; -occurs ANY (0-N) times return 0; } -statement inside (other) functions body Typical loop for } processing all elements of an array

9 5/24/2016

Example: arguments are passed by copying Function prototype values !

• The first line of the function definition #include • Contains everything that others need to know about the function void gcd (int u, int v) • void calculateTriangularNumber (int n) { • arguments (parameters): a kind of input for the function blackbox int temp; • In the function definition : formal arguments (formal parameters) printf ("The gcd of %i and %i is ", u, v); – Formal parameter: a name that is used inside the function body to refer to its argument while ( v != 0 ) { The formal • In the function call : actual arguments (actual parameters) temp = u % v; parameters u and v • The actual arguments are values are assigned to the corresponding formal u = v; are assigned new parameters. v = temp; values in the • The actual argument can be a constant, a variable, or an even more elaborate } expression. function printf ("%i\n", u); • The actual argument is evaluated, and its value is copied to the corresponding } formal parameter for the function. The actual – Because the called function works with data copied from the calling function, the int main (void) original data in the calling function is protected from whatever manipulations the called { parameters x and y are not changed ! function applies to the copies . int x=10,y=15; gcd (x, y); printf(“x=%i y=%i \n”,x,y); return 0; }

Example: of local variables Example: function declaration

#include #include void f1 (float x) { int n=6; void printMessage (void) ; Function declaration (prototype) printf(“%f \n”, x+n); (has to be before the calling function) } int f2(void) { int main (void) float n=10; { printf(“%f \n”,n); printMessage (); } Function calls printMessage (); int main (void) return 0; { } int n=5; f1(3); void printMessage (void) f2(); { Function definition return 0; printf ("Programming is fun.\n"); (can be after the } } calling function)

10 5/24/2016

#include now explained Passing arrays as parameters

• #include • A whole array can be one parameter in a function • #include < filename > is a preprocessor directive • In the function declaration, you can then omit the specification of the • Preprocessor: a first step in the C compilation process number of elements contained in the formal parameter array. • Preprocessor statements are identified by the pound sign # that must be the first – The C compiler actually ignores this part of the declaration anyway; all the nonspace character of a line compiler is concerned with is the fact that an array is expected as an argument to • The # will insert in place the contents of the specified file the function and not how many elements are in it. • These files usually have names that end with .h (header files) • Example: a function that returns the minimum value from an array given as • Header files usually contain declarations and definitions that are used by several parameter programs – int minimum (int values[10]); • contains the declarations for the standard input output functions • We must modify the function definition if a different array size is needed ! printf , scanf , getchar , etc. This is why any program that uses these – int minimum (int values[]); functions has to include • Syntactically OK, but how will the function know the actual size of the array ?! – int minimum (int values[], int numberOfElements);

Example: Passing arrays as parameters Array parameters are passed by reference !

// Function to find the minimum value in an array • If a function changes the value of an array element, that change is made #include int minimum (int values[10]) { to the original array that was passed to the function. This change remains int minValue, i; in effect even after the function has completed execution and has minValue = values[0]; returned to the calling routine. for ( i = 1; i < 10; ++i ) • Parameters of non-array type: passed by copying values if ( values[i] < minValue ) minValue = values[i]; • Parameters of array type: passed by reference return minValue; – the entire contents of the array is not copied into the formal parameter array. } the function gets passed information describing where in the computer’s int main (void) { – int scores[10], i, minScore; memory the original array is located. printf ("Enter 10 scores\n"); – Any changes made to the formal parameter array by the function are actually for ( i = 0; i < 10; ++i ) made to the original array passed to the function, and not to a copy of the scanf ("%i", &scores[i]); array. minScore = minimum (scores); printf ("\nMinimum score is %i\n", minScore); return 0; }

11 5/24/2016

Example: multidimensional array as Multidimensional arrays and functions function parameter

• When declaring a single-dimensional array as a formal parameter inside a function, the actual dimension of the array is not needed; simply use a pair of empty The number of brackets to inform the C compiler that the parameter is, in fact, an array. columns must be specified ! • This does not totally apply in the case of multidimensional arrays. For a two- No generic matrix display function possible ! dimensional array, the number of rows in the array can be omitted, but the declaration must contain the number of columns in the array. void displayMatrix (int matrix[3][5]) { • Valid examples: int row, column; for ( row = 0; row < 3; ++row) { function(int array_values[100][50]); for ( column = 0; column < 5; ++column ) function(int array_values[][50]); printf ("%5i", matrix[row][column]); • Invalid examples: printf ("\n"); function(int array_values[100][]); } function(int array_values[][]); }

Global variables Example: global variables

• A global variable declaration is made outside of any function. #include • It does not belong to any particular function. Any function in the program can then access the value of that variable and can change its value. int x; • The primary use of global variables is in programs in which many functions void f1 (void) { must access the value of the same variable. Rather than having to pass the x++; value of the variable to each individual function as an argument, the } function can explicitly reference the variable instead. • There is a drawback with this approach: Because the function explicitly void f2 (void) { references a particular global variable, the generality of the function is x++; somewhat reduced ! }

• Global variables do have default initial values: zero int main(void) { x=7; f1(); f2(); printf(“x=%i \n”,x); }

12 5/24/2016

Automatic and static variables Example: Automatic and static variables

• Automatic local variables : // Program to illustrate static and automatic variables – an automatic variable disappears after the function where it is defined completes execution, the value of that variable disappears along with it. #include – the value an automatic variable has when a function finishes execution is void auto_static (void) guaranteed not to exist the next time the function is called. { – The value of the expression is calculated and assigned to the automatic local int autoVar = 1; variable each time the function is called. • Static local variables: static int staticVar = 1; – If you place the word static in front of a variable declaration printf ("automatic = %i, static = %i\n", autoVar, staticVar); – “something that has no movement” ++autoVar; – a static —it does not come and go as the function is called and ++staticVar; returns.This implies that the value a has upon leaving a function } is the same value that variable will have the next time the function is called. int main (void) – Static variables also differ with respect to their initialization. A static, local variable is initialized only once at the start of overall program execution—and { not each time that the function is called. Furthermore, the initial value int i; specified for a static variable must be a simple constant or constant expression. Static variables also have default initial values of zero, unlike for ( i = 0; i < 5; ++i ) automatic variables, which have no default initial value. auto_static (); return 0; }

The concept of structures Example: structures

struct date • Structure: a tool for grouping heterogenous elements together. Defines type struct date , with 3 fields of type int { The names of the fields are local in the context • Array: a tool for grouping homogenous elements together int month; of the structure. • Example: storing calendar dates (day, month, year) int day; A struct declaration defines a type: if not followed by a int year; • Version1: using independent variables: list of variables it reserves no storage; it merely }; describes a template or shape of a structure. • int month = 9, day = 25, year = 2004; • Using this method, you must keep track of three separate variables for each date that you use in the program—variables that are logically related. struct date today, purchaseDate; Defines 3 variables of type struct date It would be much better if you could somehow group these sets of three variables together. This is what the structure in C allows you to do ! today.year = 2004; Accesses fields of a variable of today.month = 10; type struct date today.day = 5; A member of a particular structure is referred to in an expression by a construction of the form structurename.member

13 5/24/2016

Example: determine tomorrow’s date (Version 2) Arrays of structures

// Program to determine tomorrow's date struct time { . . . }; #include #include struct time timeUpdate (struct time now); struct date Defines type struct date as a global type int main (void) { { struct time testTimes[5] = int month; { { 11, 59, 59 }, { 12, 0, 0 }, { 1, 29, 59 }, int day; { 23, 59, 59 }, { 19, 12, 27 }}; int year; int i; }; Declares a function that takes a for ( i = 0; i < 5; ++i ) { struct date as a parameter printf ("Time is %.2i:%.2i:%.2i", testTimes[i].hour, int numberOfDays (struct date d); testTimes[i].minutes, testTimes[i].seconds); testTimes[i] = timeUpdate (testTimes[i]); int main (void) printf (" ...one second later it's %.2i:%.2i:%.2i\n", { testTimes[i].hour, testTimes[i].minutes, struct date today, tomorrow; testTimes[i].seconds); printf ("Enter today's date (mm dd yyyy): "); } scanf ("%i%i%i", &today.month, &today.day, &today.year); return 0; }

Enumerated

• You can use the enumerated type to declare symbolic names to represent integer constants. • By using the enum keyword, you can create a new "type" and specify the values it may have. • Actually, enum constants are type int; therefore, they can be used wherever you would use an int. • The purpose of enumerated types is to enhance the readability of a program. • enum primaryColor { red, yellow, blue }; • enum primaryColor myColor, gregsColor; • myColor = red; • if ( gregsColor == yellow ) …

14 5/24/2016

Example: enum The typedef statement

// Program to print the number of days in a month • C provides a capability that enables you to assign an alternate name to a data #include type . This is done with a statement known as typedef . int main (void) { typedef type_description type_name; enum month { january = 1, february, march, april, may, june,july, august, september, october, november, december • The statement }; • typedef int Counter; enum month aMonth; • defines the name Counter to be equivalent to the C data type int . Variables int days; can subsequently be declared to be of type Counter , as in the following statement: printf (“Enter month number: “); • Counter j, n; scanf (“%i”, &aMonth); • The C compiler actually treats the declaration of the variables j and n, shown in the preceding code, as normal integer variables. • The main advantage of the use of the typedef in this case is in the added readability that it lends to the definition of the variables. • the typedef statement does not actually define a new type—only a new type name.

The typedef statement Inputting character strings

• In forming a typedef definition, proceed as though a normal variable declaration • char string[81]; were being made. Then, place the new type name where the variable name would normally appear. Finally, in front of everything, place the keyword typedef: • scanf ("%s", string); typedef char Linebuf [81]; • The scanf function can be used with the %s format characters to read in a string of • characters up to a blank space, tab character, or the end of the line, whichever • defines a type called Linebuf, which is an array of 81 characters. Subsequently occurs first declaring variables to be of type Linebuf, as in • Note that unlike previous scanf calls, in the case of reading strings, the & is not • Linebuf text, inputLine; placed before the array name ! • If you type in more than 80 consecutive characters to the preceding program typedef struct without pressing the spacebar, the tab key, or the Enter (or Return) key, scanf { overflows the character array ! int month; • scanf has no way of knowing how large its character array parrameters are ! When int day; handed a %s format, it simply continues to read and store characters until one of int year; the noted terminator characters is reached. } Date; • If you place a number after the % in the scanf format string, this tells scanf the maximum number of characters to read. • Correct use of scanf for reading strings: Date birthdays[100]; • scanf ("%80s", string);

15 5/24/2016

Example: string processing String functions

• The C library supplies several string-handling functions; You don’t have to re-write #include them from scratch ! • ANSI C uses the header file to provide the prototypes. void concat (char result[], • Most frequently used functions: strlen(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), and strncpy(). const char str1[], const char str2[]); • #include int main (void) • strcat ( s1, s2 ) { – Concatenates the character string s2 to the end of s1 , placing a null character const char s1[] = "Test " ; at the end of the final string.The function also returns s1 . const char s2[] = "works." ; • strcmp ( s1, s2 ) – Compares strings s1 and s2 and returns a value less than zero if s1 is less than char s3[20]; s2 , equal to zero if s1 is equal to s2 , and greater than zero if s1 is greater than concat (s3, s1, s2); s2 . printf ("%s\n", s3); • strcpy ( s1, s2 ) return 0; – Copies the string s2 to s1 , also returning s1 . } • strlen ( s) – Returns the number of characters in s, excluding the null character.

String functions (cont.) Pointers and addresses

• strncat ( s1, s2, n ) • a pointer is a variable whose value is a memory address – Copies s2 to the end of s1 until either the null character is reached or n • int count = 10; characters have been copied, whichever occurs first. Returns s1 . • strncmp ( s1, s2, n ) • int *int_pointer; – Performs the same function as strcmp, except that at most n characters from • int_pointer = &count; the strings are compared. • The address operator has the effect of assigning to the variable int_pointer , • strncpy ( s1, s2, n ) not the value of count , but a pointer to the variable count . – Copies s2 to s1 until either the null character is reached or n characters have been copied, whichever occurs first. Returns s1 . • We say that int_ptr "points to" count • strchr ( s, c ) • The values and the format of the numbers representing memory addresses – Searches the string s for the last occurrence of the character c. If found, a depend on the computer architecture and operating system. In order to have a pointer to the character in s is returned; otherwise, the null pointer is portable way of representing memory addresses, we need a different type than returned. integer ! • strstr ( s1, s2 ) • To print addresses: %p – Searches the string s1 for the first occurrence of the string s2 . If found, a pointer to the start of where s2 is located inside s1 is returned; otherwise, if s2 is not located inside s1 , the null pointer is returned.

16 5/24/2016

Lvalues and Rvalues Declaring pointer variables

type * variable_name; • There are two “values” associated with any variable: – An "lvalue" (left value) of a variable is the value of its address, where • it is not enough to say that a variable is a pointer. You also have to specify it is stored in memory. the type of variable to which the pointer points ! – The "rvalue" (right value) of a variable is the value stored in that – int * p1; // p1 points to an integer variable (at that address). – float * p2; // p2 points to a float • The lvalue is the value permitted on the left side of the • Exception: generic pointers (void *) indicate that the pointed data assignment operator '=' (the address where the result of type is unknown evaluation of the right side will be stored). – may be used with explicit type cast to any type (type *) – void * p; • The rvalue is that which is on the right side of the assignment statement • a=a+1

Indirection (dereferencing) operator * Example: pointers

• To reference the contents of count through the pointer variable int_pointer, you // Program to illustrate pointers use the indirection operator , which is the * as an unary prefix operator. #include *int_pointer int main (void) • If a pointer variable p has the type t *, then the expression *p has the type t { int count = 10; int *ip; // Program to illustrate pointers ip = &count; #include printf ("count = %i, *ip = %i\n", count, *ip); int main (void) *ip=4; { printf ("count = %i, *ip = %i\n", count, *ip); int count = 10, x; return 0; int *int_pointer; } int_pointer = &count; x = *int_pointer; printf ("count = %i, x = %i\n", count, x); return 0; }

17 5/24/2016

Using pointer variables NULL pointers

• Values of a pointer variable: • The value of a pointer in C is meaningless until it is set pointing to something ! – Usually the value of a pointer variable is a pointer to some other variable – Another value a pointer may have: it may be set to a null pointer int *p; Severe runtime error !!! the value 4 is stored in the location to • A null pointer is a special pointer value that is known not to point anywhere. *p = 4; which p points. But p, being uninitialized, has a random value, • How to set pointer values:so we cannot know where the 4 will be stored ! • No other valid pointer, to any other variable, will ever compare equal to a null – Using the address operator pointer ! • Predefined constant NULL, defined in int *p; • Good practice: test for a null pointer before inspecting the value pointed ! int x; p = &x; #include – Using*p directly = 4; assignements between pointer variables int *ip = NULL; int *p; int *p1; if(ip != NULL) printf("%d\n", *ip); int x; p1 = &x; if(ip ) printf("%d\n", *ip); p = p1; *p = 4;

const and pointers Pointers and Function Arguments

• With pointers, there are two things to consider: • If it is necessary that a function alters its arguments, the caller can pass – whether the pointer will be changed pointers to the values to be changed – whether the value that the pointer points to will be changed. • Pointer arguments enable a function to access and change variables in the • Assume the following declarations: function that called it char c = 'X'; char *charPtr = &c; void swap(int *px, int *py) • The pointer variable charPtr is set pointing to the variable c. /* interchange *px and *py */ • If the pointer variable is always set pointing to c, it can be declared as a const pointer as follows: { char * const charPtr = &c; int temp; *charPtr = 'Y'; // this is valid temp = *px; charPtr = &d; // not valid !!! *px = *py; • If the location pointed to by charPtr will not change through the pointer variable *py = temp; charPtr , that can be noted with a declaration as follows: } const char *charPtr = &c; charPtr = &d; // this is valid *charPtr = 'Y'; // not valid !!! int a=3, b=5; swap(&a, &b);

18 5/24/2016

Dynamic memory allocation malloc()

• Whenever you define a variable in C you are reserving one or more • locations in the computer’s memory to contain the values that will be void * malloc(int n); stored in that variable.The C compiler automatically allocates the correct • amount of storage for you. • malloc allocates n bytes of memory and returns a pointer to them if the allocation • It is frequently desirable to be able to dynamically allocate storage while a was succesful, NULL otherwise program is running: • The pointer returned by malloc is of the generic type void *; it has to be converted • Suppose you have a program that is designed to read in a set of data from to a concrete pointer type input (standard input or file) into an array in memory. Suppose, however, that you don’t know how much data is in the file until the program starts execution. You have three choices: #include – Define the array to contain the maximum number of possible elements at char *line; compile time. int linelen = 100; – Use a variable-length array to dimension the size of the array at runtime. line = (char *) malloc(linelen); – Allocate the array dynamically using one of C’s memory allocation routines. /* incomplete -- malloc's return value not checked */ getline(line, linelen);

Examples: malloc Checking what malloc returns !

• When malloc is unable to allocate the requested memory, it returns a null pointer . char *somestring, *copy; Therefore, whenever you call malloc, it's vital to check the returned pointer before ... using it ! copy = (char *) malloc(strlen(somestring) + 1); /* incomplete -- malloc's return value not checked */ strcpy(copy, somestring); int *ip = (int *)malloc(100 * sizeof(int)); if(ip == NULL) { printf("out of memory\n"); return; // exits current function int *ip = (int *) malloc(100 * sizeof(int)); }

int *ip = (int *) malloc(100 * sizeof(int)); if(ip == NULL) { printf("out of memory\n"); exit(1); // exits all calls, // terminates program }

19 5/24/2016

Example: dynamic allocation of arrays Lifetime of dynamic allocated memory

#include #include • Memory allocated with malloc lasts as long as you want it to. It does not int main(void) automatically disappear when a function returns, as automatic variables do: { int n; int * tab; void fct(void) { int i; int *p; printf("Input number of elements: \n"); p=(int*) malloc(10*sizeof(int)); scanf("%d", &n); return; if ((tab=(int *)malloc(n * sizeof(int)))==NULL) { printf(“Memory allocation error !\n"); } exit(1); } The memory area for (i=0; i

free() Binary representation of integers

• Dynamically allocated memory is deallocated with the free function. If p contains a pointer previously returned by malloc, you can call • Positive integers: • free(p); 00 0 0 0 0 0 1 0 1 • which will ``give the memory back'' to the heap of memory from which malloc requests are satisfied. • the memory you give back by calling free() is immediately usable by other parts of your program. (Theoretically, it may even be usable by other programs.) most least • When your program exits, any memory which it has allocated but not freed should Sign bit significant or significant or be automatically released by the operating system. high-order bit low-order bit • Once you've freed some memory you must remember not to use it any more. After calling free(p) it is probably the case that p still points at the same memory. However, since we've given it back, it's now ``available,'' and a later call to malloc might give that memory to some other part of your program. 1*2^0+0*2^1+1*2^2=5

20 5/24/2016

Binary representation of integers Bit operators

• Negative integers: • & Bitwise AND • | Bitwise Inclusive-OR 11 1 1 1 1 10 1 1 • ^ Bitwise Exclusive-OR • ~ Ones complement • << Left shift most least • >> Right shift Sign bit significant or significant or high-order bit low-order bit • All the operators, with the exception of the ones complement operator ~, are binary operators and as such take two operands. Steps to convert a negative number from decimal to binary: Ex: -5 • Bit operations can be performed on any type of integer value in C—be it 1. add 1 to the value: -5+1=-4 2. express the absolute value of the result in binary: 4=00000100 short, long, long long, and signed or unsigned—and on characters, but 3. then “complement” all the bits: 11111011=-5 cannot be performed on floating-point values . Steps to convert a negative number from binary to decimally: Ex: 11111011 1. complement all of the bits: 00000100 2. convert the result to decimal: 4 3. change the sign of the result, and then subtract 1: -4-1=-5

Usage: Masking bits Usage: Turning bits on

• A mask is a bit pattern with some bits set to on (1) and some bits to off (0). • Turn on (set to 1) particular bits in a value while leaving the remaining bits • Example: unchanged. • int MASK = 2; // 00000010, with only bit number 1 nonzero. • Example: an IBM PC controls hardware through values sent to ports. To turn on a • Masking bits: device (i.e., the speaker), the driver program has to turn on the 1 bit while leaving the others unchanged. • flags = flags & MASK; • This can be done with the bitwise OR operator. • all the bits of flags (except bit 1) are set to 0 because any bit combined with 0 • using the & operator yields 0. Bit number 1 will be left unchanged. (If the bit is 1, The MASK has bit 1 set to 1, other bits 0 1 & 1 is 1; if the bit is 0, 0 & 1 is 0.) This process is called "using a mask" because • int MASK = 2; // 00000010, with only bit number 1 nonzero. the zeros in the mask hide the corresponding bits in flags. • The statement • you can think of the 0s in the mask as being opaque and the 1s as being • flags = flags | MASK; transparent. The expression flags & MASK is like covering the flags bit pattern • sets bit number 1 in flags to 1 and leaves all the other bits unchanged. This with the mask; only the bits under MASK's 1s are visible follows because any bit combined with 0 by using the | operator is itself, and any bit combined with 1 by using the | operator is 1.

21 5/24/2016

Usage: Turning bits off Usage: Toggling bits

• Turn off (set to 0) particular bits in a value while leaving the remaining • Toggling a bit means turning it off if it is on, and turning it on if it is off. bits unchanged. • To toggle bit 1 in flag : • Suppose you want to turn off bit 1 in the variable flags . • The MASK has bit 1 set to 1, other bits 0 • The MASK has bit 1 set to 1, other bits 0 • int MASK = 2; // 00000010, with only bit number 1 nonzero. • int MASK = 2; // 00000010, with only bit number 1 • flag = flag ^ MASK; nonzero. • You can use the bitwise EXCLUSIVE OR operator to toggle a bit. • The statement: • The idea is that if b is a bit setting (1 or 0), then 1 ^ b is 0 if b is 1 and is 1 if b • flags = flags & ~MASK; is 0. Also 0 ^ b is b, regardless of its value. • Because MASK is all 0s except for bit 1, ~MASK is all 1s except for bit 1. A • Therefore, if you combine a value with a mask by using ^, values corresponding 1 combined with any bit using & is that bit, so the statement leaves all to 1s in the mask are toggled, and values corresponding to 0s in the mask are the bits other than bit 1 unchanged. Also, a 0 combined with any bit unaltered. using & is 0, so bit 1 is set to 0 regardless of its original value.

Usage: Checking value of a bit The Left Shift Operator

•the bits contained in the value • For example: does flag has bit 1 set to 1? are shifted to the left a number of • you must first mask the other bits in flag so that you compare only bit 1 of flag places (bits) int a=25; with MASK : •Bits that are shifted out through • if ((flag & MASK) == MASK) the high-order bit of the data item printf(“%x %x”,a,a<<1); • are lost, • 0s are always shifted in through the low-order bit of the value. shifted to the left. Associated with this Bit lost 00 0 0 00 0 0 1 1 0 0 1 a : 0x19

0 0 0 0 00 0 1 1 0 0 1 0 a<<1 : 0x32

22