3. Course Objective After completing this course, you will be able to: Write programs in C language Understand what are the constructs of the C language Implement data structures and algorithms in C Amr Ali Abdel-Naby@2011 Introduction to C Programming 3
4. Course Notes Set your cell phone to vibrate. I assume you know computer architecture. Ask any time. During labs, feel free to: Check any material Search internet Amr Ali Abdel-Naby@2011 Introduction to C Programming 4
5. Course References www.cprogramming.com C by Example www.opengroup.com http://ocw.mit.edu/index.htm Amr Ali Abdel-Naby@2011 Introduction to C Programming 5
6. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 6
7. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 7
8. What is C? Invented by Dennis Ritchie – AT&T Bell Labs 1972 Widely used today Extends to newer system architectures Efficiency/performance Low-level access Amr Ali Abdel-Naby@2011 Introduction to C Programming 8
9. C Features Few keywords Structures, unions, compound data types.. Pointers, arrays… Standard library Compiles to native code Macro preprocessor Amr Ali Abdel-Naby@2011 Introduction to C Programming 9
10. C Evolution 1972 – C Invention 1978 – 1st specification published 1989 – C89 standard (ANSI C or standard C) 1990 – ANSI C adopted by ISO, AKA C90 1999 – C99 standard Not completely implemented in many compilers 2007 – Work on new standard C1X announced We will focus on ANSI/ISO C (C89/C90) Amr Ali Abdel-Naby@2011 Introduction to C Programming 10
11. C Usage Systems programming Operating systems Microcontrollers Embedded processors DSP processors Amr Ali Abdel-Naby@2011 Introduction to C Programming 11
12. C vs. Others Recent derivatives: C++, C#, Objective-C Had an effect on: Java, Perl, Python C lacks: Exceptions Range checking Garbage collection OOP … Lower level language Amr Ali Abdel-Naby@2011 Introduction to C Programming 12
13. Editing C Code *.c extension for C source files *.h extension for C header files They are editable by any text editor. Amr Ali Abdel-Naby@2011 Introduction to C Programming 13
14. IDE – All in One Solution Examples: Eclipse CDT MS VC++ express edition KDevelop Xcode Compiler, editor, debugger… Suitable for large programs Amr Ali Abdel-Naby@2011 Introduction to C Programming 14
15. Structure of a C File Amr Ali Abdel-Naby@2011 Introduction to C Programming 15
16. Comments Ignored by the compiler Can appear anywhere Amr Ali Abdel-Naby@2011 Introduction to C Programming 16
17. The #include Macro A header file has constants, functions, and other declarations. #include reads the contents of the header file #include <header-file> searches for the header file in the include paths #include “header-file” searches for the header file in the current directory where the file it included it is in Amr Ali Abdel-Naby@2011 Introduction to C Programming 17
18. Declaring variables Must declare variables before use General form: type variable_name [=initial_value][,][…]; Uninitialized, variable assumes a default value Can declare/initialize multiple variables at once Amr Ali Abdel-Naby@2011 Introduction to C Programming 18
20. Order of Operations Orders of Operation Use parentheses to override order of evaluation Amr Ali Abdel-Naby@2011 Introduction to C Programming 20
21. Function Prototypes Functions also must be declared before use Declaration called function prototype Prototypes for many common functions in header files for C Standard Library General form: return_type function_name(arg1, arg2, …) Amr Ali Abdel-Naby@2011 Introduction to C Programming 21
22. The main() Function C Program entry point Can be one of: Amr Ali Abdel-Naby@2011 Introduction to C Programming 22
23. Function Definition Must match prototype (if there is one) Variable names don’t have to match Curly braces define a block Variables declared in a block exist only in that block Variable declarations must be before any other statements Amr Ali Abdel-Naby@2011 Introduction to C Programming 23
24. Our First Program Amr Ali Abdel-Naby@2011 Introduction to C Programming 24
25. More About Strings Strings stored as character array Null-terminated Last character in array is ‘’ Not written explicitly in string literals Special characters specified using escape character): - backslash, - apostrophe, - quotation mark , , , - backspace, tab, carriage return, linefeed oo, hh - octal and hexadecimal ASCII character codes 41 – ’A’, 60 – ’0’ Amr Ali Abdel-Naby@2011 Introduction to C Programming 25
26. Console IO stdout, stdin: console output and input streams puts(string): print string to stdout putchar(char): print character to stdout char = getchar(): return character from stdin string = gets(string): read line from stdin into string Amr Ali Abdel-Naby@2011 Introduction to C Programming 26
27. Preprocessor Macros They begin with #. They can take arguments. Parentheses ensure order of operations. Compiler performs inline replacement. Amr Ali Abdel-Naby@2011 Introduction to C Programming 27
28. Conditional Preprocessor Macros They can control which lines are compiled. Evaluated before code itself is compiled, so conditions must be preprocessor defines or literals Used in header files to ensure declarations happen only once Amr Ali Abdel-Naby@2011 Introduction to C Programming 28
29. Extra Preprocessor Macros Preprocessor directive Trigger a custom compiler error/warning message Remove the definition of a previously defined constant Amr Ali Abdel-Naby@2011 Introduction to C Programming 29
30. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 30
31. Definitions Datatype Determines the set of values an object can have and what operations that can be performed on it Operator Specifies how an object can be manipulated Expression Combination of values, variables, operators, and functions Variable Named link/reference to a value stored in the system’s memory or an expression that can be evaluated Amr Ali Abdel-Naby@2011 Introduction to C Programming 31
32. Variables Naming Rules Can contain letters, digits and _ Should start with letters Keywords (e.g., for,while etc.) cannot be used as variable names. Names are case sensitive. X is not as x. Amr Ali Abdel-Naby@2011 Introduction to C Programming 32
33. Data Types C has a small family of datatypes. Numeric (int, float, double) Character (char) User defined (struct, union) Numeric datatypes Amr Ali Abdel-Naby@2011 Introduction to C Programming 33
34. Variables Sizes and Endianess Sizes are machine/compiler dependent. sizeof(char) < sizeof(short) <= sizeof(int) <= sizeof(long) sizeof(char) < sizeof(short) <= sizeof(float) <= sizeof(double) For datatypes spanning multiple bytes, the order of arrangement of the individual bytes is important. Big endian vs. little endian Amr Ali Abdel-Naby@2011 Introduction to C Programming 34
35. Big Endian vs. Little Endian Amr Ali Abdel-Naby@2011 Introduction to C Programming 35
36. Constants Literal/fixed values assigned to variables or used directly in expressions Integers 3, 3UL, 0x12, 012 Floating point 3.141, 3.141F Character ‘A’, ‘41’, ‘101’ String “Hello world”, “Hello” “world” Enumeration enum bool{YES, NO}, enum color{R=1, G, B, Y=10} Amr Ali Abdel-Naby@2011 Introduction to C Programming 36
37. Operators Arithmetic +, -, *, /, % Relational >, >=, <, <=, ==, != Logical &&, ||, ! Increment and decrement X++, Y— --X, ++X Bitwise &, |, ^, ~, >>, << Assignment +=, &=… Amr Ali Abdel-Naby@2011 Introduction to C Programming 37
39. Type Conversions C is a weakly typed language. It allows implicit conversions as well as forced casting. When variables are promoted to higher precision, data is preserved. char int int float As a rule (with exceptions), the compiler promotes each term in an binary expression to the highest precision operand. Amr Ali Abdel-Naby@2011 Introduction to C Programming 39
40. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 40
41. Blocks and Compound Statements Curly braces {} combine statements into a compound statement/block A block substitute a simple statement and compiled as a single unit. Variables can be declared in a block. A block can be empty or nested. Amr Ali Abdel-Naby@2011 Introduction to C Programming 41
42. Examples Amr Ali Abdel-Naby@2011 Introduction to C Programming 42
43. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 43
44. Booleans in C No booleans in C True is any non-zero value/result of a condition/expression. False is any zero value/result of a condition/expression. Expression must be numeric or a pointer. Amr Ali Abdel-Naby@2011 Introduction to C Programming 44
45. The if Statement Amr Ali Abdel-Naby@2011 Introduction to C Programming 45
47. The while Loop Amr Ali Abdel-Naby@2011 Introduction to C Programming 47
48. The for Loop Amr Ali Abdel-Naby@2011 Introduction to C Programming 48
49. The do-while Loop Amr Ali Abdel-Naby@2011 Introduction to C Programming 49
50. The break and continue Keywords break exists the innermost loop or switch statement. continue skips rest of innermost loop body, jumping to loop condition . Amr Ali Abdel-Naby@2011 Introduction to C Programming 50
51. goto Keyword Allows you to jump unconditionally to arbitrary part of your code (within the same function) The location is identified using a label. A label is a named location in the code. It has the same form as a variable followed by a ’:’ . Do not use it. Amr Ali Abdel-Naby@2011 Introduction to C Programming 51
52. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 52
53. Divide and Conquer Let’s design a program to solve linear Diophantine equation. ax + by = c where a, b, c, x, y are integers get a, b, c from command line compute g = gcd(a,b) if (c is not a multiple of the gcd) no solutions exist; Run Extended Euclidean algorithm on a, b rescale x and y output by (c/g) print solution Extended Euclidean algorithm: finds integers x, y s.t. ax + by = gcd(a, b). Amr Ali Abdel-Naby@2011 Introduction to C Programming 53
54. Returning Multiple Values Extended Euclidean algorithm returns gcd, and two other state variables, x and y Functions only return (up to) one value Solution: Use global variables Declare variables for other outputs outside the function. Variables declared outside of a function block are global. Persist throughout life of program Can be accessed/modified in any function Amr Ali Abdel-Naby@2011 Introduction to C Programming 54
55. In General Break down problem into simpler sub-problems. Consider iteration and recursion. Writing pseudocode first can help. Amr Ali Abdel-Naby@2011 Introduction to C Programming 55
56. Programming Modules in C C programs do not need to be monolithic. Module: interface and implementation Interface: header files Implementation: auxiliary source/object files Same concept carries over to external libraries. Lets take the extended Euclid as an example. Amr Ali Abdel-Naby@2011 Introduction to C Programming 56
57. ecluid.c Amr Ali Abdel-Naby@2011 Introduction to C Programming 57
58. ecluid.h Amr Ali Abdel-Naby@2011 Introduction to C Programming 58
59. Using Euclid Module Amr Ali Abdel-Naby@2011 Introduction to C Programming 59
60. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 60
61. Variable Scope The region in which a variable is valid. Many cases, corresponds to block with variable’s declaration Variables declared outside of a function have global scope Function definitions also have scope Amr Ali Abdel-Naby@2011 Introduction to C Programming 61
62. Scope and Nested Declarations Amr Ali Abdel-Naby@2011 Introduction to C Programming 62
63. Static Variables static keyword has two meanings, depending on where the static variable is declared Outside a function, static variables/functions only visible within that file Not global (cannot be extern’ed) Inside a function, static variables are local to that function Initialized only during program initialization Do not get reinitialized with each function call Amr Ali Abdel-Naby@2011 Introduction to C Programming 63
64. Register Variables During execution, data are processed in registers. Explicitly store commonly used data in registers Minimize load/store overhead Can explicitly declare certain variables as registers using register keyword Must be a simple type Only local variables and function arguments eligible excess/unallowed register declarations ignored, Registers do not reside in addressed memory Pointer of a register variable illegal Amr Ali Abdel-Naby@2011 Introduction to C Programming 64
65. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 65
66. Preliminaries IO facilities are provided by the standard library <stdio.h> and not by the language itself. A text stream consists of a series of lines ending with ’’. The standard library takes care of conversion from ’’−’’ . A binary stream consists of a series of raw bytes. The streams provided by standard library are buffered. Amr Ali Abdel-Naby@2011 Introduction to C Programming 66
67. Standard IO Amr Ali Abdel-Naby@2011 Introduction to C Programming 67
68. Formatted Output: printf It takes in a variable number of arguments. It returns the number of characters printed. The format can contain literal strings as well as format specifiers (starts with %). Amr Ali Abdel-Naby@2011 Introduction to C Programming 68
69. printf Format Specification - type %[flags][width][. precision][length]<type> Amr Ali Abdel-Naby@2011 Introduction to C Programming 69
70. printf Format Specification - width %[flags][width][. precision][length]<type> Amr Ali Abdel-Naby@2011 Introduction to C Programming 70
71. printf Format Specification - flag %[flags][width][. precision][length]<type> Amr Ali Abdel-Naby@2011 Introduction to C Programming 71
72. printf Format Specification - precision %[flags][width][. precision][length]<type> Amr Ali Abdel-Naby@2011 Introduction to C Programming 72
73. printf Format Specification - modifier %[flags][width][. precision][length]<type> Amr Ali Abdel-Naby@2011 Introduction to C Programming 73
74. Character Arrays Strings are represented as an array of characters. C does not restrict the length of the string. The end of the string is specified using 0. “hello” {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘’} Amr Ali Abdel-Naby@2011 Introduction to C Programming 74
75. Comparing Strings strcmp in string.h compares two strings in dictionary order. Lower case letters come after capital case. ‘a’ > ‘A’ The function returns a value <0 if s comes before t The function return a value 0 if s is the same as t The function return a value >0 if s comes after t Amr Ali Abdel-Naby@2011 Introduction to C Programming 75
76. Formatted Input scanf reads characters from standard input, interpreting them according to format specification Similar to printf , scanf also takes variable number of arguments. Arguments have to be address of variables. The format specification is the same as that for printf . When multiple items are to be read, each item is assumed to be separated by white space. scanf ignores white spaces. It returns the number of items read or EOF. Amr Ali Abdel-Naby@2011 Introduction to C Programming 76
77. String IO Formatted data can be written to or read from character arrays. Amr Ali Abdel-Naby@2011 Introduction to C Programming 77
78. File IO C allows us to read/write data from text/binary files. We can: Open a file Close a file Read a single character Read a single line Write a single character Write a single line Read formatted line Write formatted line Amr Ali Abdel-Naby@2011 Introduction to C Programming 78
79. Project I: Game of Life Amr Ali Abdel-Naby@2011 Introduction to C Programming 79 Required: In lab-01.pdf, solve all problems. Duration: 120 minutes
80. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 80
81. Physical vs. Virtual Memory Physical memories are physical resources where data can be stored. Caches RAMs Hard disks Removable storage Virtual memory is an OS abstracted addressable space accessible by your code. Amr Ali Abdel-Naby@2011 Introduction to C Programming 81
82. Physical Memory Considerations Different sizes and access speeds Memory management is a major OS function. You have to optimize your code to make the best usage of the physical memory. OS moves data around physical memory during execution. In embedded systems, it may be very limited. Amr Ali Abdel-Naby@2011 Introduction to C Programming 82
83. Virtual Memory How much physical memory do you have? How much virtual memory do you have? Depends on OS Usable parts of virtual memory are stack and heap. Amr Ali Abdel-Naby@2011 Introduction to C Programming 83
84. Addressing Variables Every variables has an address in memory. What does not have an address? Register variables Expressions unless result is a variable. Constants, literals, and preprocessors The & operator finds the address of a variable. Address of a variable of type t has type t *. Amr Ali Abdel-Naby@2011 Introduction to C Programming 84
85. Dereferencing Pointers Using the * operator, I can access and modify addressed variable. A pointer that dereferences nothing is called a NULL pointer. Amr Ali Abdel-Naby@2011 Introduction to C Programming 85
86. Casting Pointers Explicitly from any type to any type. Implicitly to and from void *. May cause segmentation faults and many difficult errors to debug. Amr Ali Abdel-Naby@2011 Introduction to C Programming 86
87. Functions with Multiple Outputs Recall extended Ecluid, it calculates g = gcd(a,b) and sets the global variables x and y. Using pointers we can, extend the outputs of a function. Amr Ali Abdel-Naby@2011 Introduction to C Programming 87
89. Variable Passing Out of Scope What is wrong with this code? Amr Ali Abdel-Naby@2011 Introduction to C Programming 89
90. Pointer to Pointers Address stored by a pointer is also data in memory. A pointer to a pointer can address location of address in memory. Uses in C: Pointer arrays String arrays Amr Ali Abdel-Naby@2011 Introduction to C Programming 90
91. Pointer to Pointers Example Amr Ali Abdel-Naby@2011 Introduction to C Programming 91 vs.
92. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 92
93. Arrays and Pointers Arrays in C are implemented using a pointer to block of contiguous memory. [] can be used for accessing array elements. Array name is a pointer to its 1st element. Not modifiable/reassignable like any pointer. Amr Ali Abdel-Naby@2011 Introduction to C Programming 93
94. The sizeof() Operator Can be used to find the byte size of: A primitive type/variable Primitive arrays How to find array length? Amr Ali Abdel-Naby@2011 Introduction to C Programming 94
95. Pointer Arithmetic A pointer is not an integer but we can add/substract an integer from it. pa + i points to arr[i]; Address value increments by i x size of data type. If arr[0] has address 100, then pa + 3 has value of 112. Amr Ali Abdel-Naby@2011 Introduction to C Programming 95
96. Strings as Arrays Strings are null terminated character arrays. There are some utilities defined in string.h. strcpy strncpy strcmp strncmp strlen strcat strncat strchr strrchr … Amr Ali Abdel-Naby@2011 Introduction to C Programming 96
97. Pointer Arrays Array of pointers Each pointer can point to another array. Example usage: An array int arr[100] that we want to sort without modifying Solution: Declare a pointer array int * sorted_arr[100] containing pointers to elements of arr. Sort the pointers instead of the numbers themselves. Good approach for sorting arrays whose elements are very large. Amr Ali Abdel-Naby@2011 Introduction to C Programming 97
98. String Arrays An array of strings, each stored as a pointer to an array of chars. Amr Ali Abdel-Naby@2011 Introduction to C Programming 98
99. Multidimensional Arrays C also permits multidimensional arrays specified using []. Higher dimensions are possible. Multidimensional arrays are rectangular. Pointer arrays can be arbitrary shaped. Amr Ali Abdel-Naby@2011 Introduction to C Programming 99
100. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 100
101. Linear Search Amr Ali Abdel-Naby@2011 Introduction to C Programming 101
102. Binary Search Amr Ali Abdel-Naby@2011 Introduction to C Programming 102
103. Binary Search cont’d Requires random access to array memory Slow on sequential devices like hard disks May be wasteful Linear search may be useful in some cases. Implemented in C standard library bsearch in stdlib.h Amr Ali Abdel-Naby@2011 Introduction to C Programming 103
104. Simple Sort Iterate through an array until an out of order element found. Insert out of order element into correct location. Repeat until end of array reached. Amr Ali Abdel-Naby@2011 Introduction to C Programming 104
105. Finding Out of Order Elements Amr Ali Abdel-Naby@2011 Introduction to C Programming 105
106. Shifting Out of Order Elements Amr Ali Abdel-Naby@2011 Introduction to C Programming 106
107. Quick Sort Choose a pivot element. Move all elements less than pivot to one side. Greater ones are on other side. Sort sides individually. Implemented in C standard library qsort in stdlib.h Amr Ali Abdel-Naby@2011 Introduction to C Programming 107
108. Quick Sort cont’d Not stable Equal-valued elements can get switched. Can sort in-place Desirable for low-memory environments Choice of pivot influences performance. Easily parallelizable Recursive Can cause stack overflow on large array Amr Ali Abdel-Naby@2011 Introduction to C Programming 108
109. Exercise 4 Required: In assn-04.pdf, solve all problems except 4.3. Duration: 20 minutes Amr Ali Abdel-Naby@2011 Introduction to C Programming 109
110. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 110
111. Structure A collection of related variables grouped under a single name. Amr Ali Abdel-Naby@2011 Introduction to C Programming 111
112. Structure cont’d struct defines a new data type. The name of the structure is optional. The variables declared within a structure are called its members. Variables can be declared like any other built in data-type. Initialization is done by specifying values of every member. Assignment operator copies every member of the structure. Be careful with pointers. Amr Ali Abdel-Naby@2011 Introduction to C Programming 112
113. Accessing Structure Members The . operator is used to access structure members. Amr Ali Abdel-Naby@2011 Introduction to C Programming 113
114. Structure Pointers Structures are copied element wise. For large structures it is more efficient to pass pointers. Members can be accesses from structure pointers using the -> operator. Amr Ali Abdel-Naby@2011 Introduction to C Programming 114
115. Array of Structures Amr Ali Abdel-Naby@2011 Introduction to C Programming 115
116. Size of Structures The size of a structure is greater than or equal to the sum of the sizes of its members. Alignment and padding are issues. Libraries Precompiled files SIMD instructions Members can be explicitly aligned or padded using compiler extensions. Amr Ali Abdel-Naby@2011 Introduction to C Programming 116
117. Union May hold objects of different types/sizes in the same memory location. Union size is equal to the size of its largest element. The compiler does not test if the data is being read in the correct format. Amr Ali Abdel-Naby@2011 Introduction to C Programming 117
118. Bit Fields A bit-field is a set of adjacent bits within a single word. It must be unsigned int. The number after: specifies the width Amr Ali Abdel-Naby@2011 Introduction to C Programming 118
119. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 119
120. Dynamic Memory Allocation malloc() allocates an uninitialized block of memory. calloc() allocates a zero initialized array of n elements. free() frees allocated memory. Common errors: Accessing freed memory Accessing uninitialized pointer Memory leak Amr Ali Abdel-Naby@2011 Introduction to C Programming 120
121. Linked List A dynamic data structure that consists of a sequence of records where each element contains a link to the next and may be previous record in the sequence. They can be: Single Double Circular Amr Ali Abdel-Naby@2011 Introduction to C Programming 121
122. Single Linked List Every node has a payload and a link to the next node in the list. The start (head) of the list is maintained in a separate variable. End of the list is indicated by NULL (sentinel). Amr Ali Abdel-Naby@2011 Introduction to C Programming 122
123. Single Linked List Utilities Amr Ali Abdel-Naby@2011 Introduction to C Programming 123
124. Binary Tree A dynamic data structure where each node has at most two children. A binary search tree is a binary tree with ordering among its children. Usually, all elements in the left subtree are less than the root element while elements in the right subtree are greater than the root element. Amr Ali Abdel-Naby@2011 Introduction to C Programming 124
125. Binary Tree Utilities Can be framed as recursive Traversal (printing, searching): Pre-order: root, left subtree, right subtree In order: left subtree, root, right subtree Post order: left subtree , right subtree, root Amr Ali Abdel-Naby@2011 Introduction to C Programming 125
126. Exercise 5 Required: In assn-05.pdf, solve all problems. Duration: 60 minutes Amr Ali Abdel-Naby@2011 Introduction to C Programming 126
127. Stack A special type of list where we read and write from same end of list. LIFO list Push operation writes to list end. POP operation reads from list end. Can be build as an array or as a linked list. Amr Ali Abdel-Naby@2011 Introduction to C Programming 127
128. Stack as an Array Amr Ali Abdel-Naby@2011 Introduction to C Programming 128
129. Stack as a Linked List Amr Ali Abdel-Naby@2011 Introduction to C Programming 129
130. Queue A special type of list where we read and write from different ends of list. FIFO list Enqueue operation writes to list end. Dequeue operation reads from other list end. Can be build as an array or as a linked list. Amr Ali Abdel-Naby@2011 Introduction to C Programming 130
131. Queue as an Array Amr Ali Abdel-Naby@2011 Introduction to C Programming 131
132. Queue as a Linked List Amr Ali Abdel-Naby@2011 Introduction to C Programming 132
133. B Tree Generalized binary search tree, used for databases and file systems With variable number of children Tree is balanced. All leaves at same level A node contains a list of keys to divide range of elements in children. Initially, it contains a root node with no children. Amr Ali Abdel-Naby@2011 Introduction to C Programming 133
134. Inserting Elements Complicated due to maximum number of keys At high level: Traverse tree to leaf node If leaf full, split into two Move median key element into parent and split parent if already full Split remaining keys into 2 leaves Add elements to sorted list of keys Can be done in one pass by splitting full parents during traversal in step 1 Amr Ali Abdel-Naby@2011 Introduction to C Programming 134
137. Searching a B Tree Like searching a B Tree Start at root If node empty, element not in tree Search list of keys for element (using linear or binary search) If element in list, return element Otherwise, element between keys, and repeat search on child node for that range Amr Ali Abdel-Naby@2011 Introduction to C Programming 137
138. Deleting Elements Complicated due to minimum number of children restriction You need to ensure child nodes to be traversed have enough keys If adjacent child node has at least t keys, move separating key from parent to child and closest key in adjacent child to parent If no adjacent child nodes have extra keys, merge child node with adjacent child When removing a key from a node with children, need to rearrange keys again If child before or after removed key has enough keys, move closest key from child to parent If neither child has enough keys, merge both children If child not a leaf, have to repeat this process Amr Ali Abdel-Naby@2011 Introduction to C Programming 138
141. Priority Queue A queue where ordering data by priority, used for sorting, event simulation, and many other algorithms Elements enqueued with priority, dequeued in order of highest priority Common implementations: heap or binary search tree Amr Ali Abdel-Naby@2011 Introduction to C Programming 141
142. Heaps A tree with high-ordering property Child priority ≤ Parent priority Usually implemented as an array with top element at beginning Amr Ali Abdel-Naby@2011 Introduction to C Programming 142
143. Extracting Data Maximum priority element at top of heap Can peek by looking at top element We can remove top element, move last element to top, and swap top element down with its children until it satisfies heap-ordering property: Start at top Find largest of element and children; if element is largest, we are done Otherwise, swap element with largest child and repeat with element in new position Amr Ali Abdel-Naby@2011 Introduction to C Programming 143
144. Inserting Data/Increasing Priority Element is inserted at the end. Increase priority of element to real priority. Start at element If new priority less than parent’s, we are done. Otherwise, swap element with parent and repeat. Amr Ali Abdel-Naby@2011 Introduction to C Programming 144
146. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 146
147. Void Pointers C does not allow to declare and usage of void pointers. Can be used as a return type or as a function parameter C allows void pointers. The can point to any data point. They can’t be dereferenced. They must be cast before used. Amr Ali Abdel-Naby@2011 Introduction to C Programming 147
148. Function Pointers In C, function itself is not a variable. It is possible to declare pointer to functions. Declaration examples: Function pointers can be assigned, pass to and from functions, placed in arrays etc. Amr Ali Abdel-Naby@2011 Introduction to C Programming 148
149. Callbacks A piece of executable code passed to functions. Callbacks are implemented by passing function pointers. Example: qsort() can sort an array of any data type. qsort() calls a function whenever a comparison needs to be done. Callback The callback returns <0, 0, or >0 depending on iinputs. Amr Ali Abdel-Naby@2011 Introduction to C Programming 149
150. qsort Callback Amr Ali Abdel-Naby@2011 Introduction to C Programming 150
151. Linked List Callback We can make a callback that iterates a function through the list. Amr Ali Abdel-Naby@2011 Introduction to C Programming 151
152. Printing and Counting Nodes Amr Ali Abdel-Naby@2011 Introduction to C Programming 152
153. Array of Function Pointers Amr Ali Abdel-Naby@2011 Introduction to C Programming 153
154. Array of Function Pointers cont'd Amr Ali Abdel-Naby@2011 Introduction to C Programming 154
155. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 155
156. Hash Table Combines linked lists and arrays to provide an efficient structure for storing dynamic data. They are commonly implemented as an array of linked lists. Amr Ali Abdel-Naby@2011 Introduction to C Programming 156
157. Hash Table cont'd Each data item is associated with a key that determines its location. Hash functions are used to generate an evenly distributed hash value. A hash collision is said to occur when two items have the same hash value. Items with the same hash keys are chained Amr Ali Abdel-Naby@2011 Introduction to C Programming 157
158. Hash Functions A hash function maps its input into a finite range: hash value, hash code. The hash value should ideally have uniform distribution. Other uses of hash functions: cryptography, caches (computers/internet)… Hash function types: Division type Multiplication type … Amr Ali Abdel-Naby@2011 Introduction to C Programming 158
159. Hash Table Example Amr Ali Abdel-Naby@2011 Introduction to C Programming 159
160. Hash Table Example Amr Ali Abdel-Naby@2011 Introduction to C Programming 160
161. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 161
162. Symbols and Libraries External libraries provide a wealth of functionality . C standard library Programs access libraries’ functions and variables via identifiers known as symbols. Header file declarations/prototypes mapped to symbols at compile time. Symbols linked to definitions in external libraries during linking. Our own program produces symbols too. Amr Ali Abdel-Naby@2011 Introduction to C Programming 162
163. Functions and Variables as Symbols What variables and functions are declared globally? Amr Ali Abdel-Naby@2011 Introduction to C Programming 163
165. Static and Dynamic Linking Functions, global variables must be allocated memory before used. Can allocate at compile time (static) or at run time (shared) Static linking links symbols in .o files and .lib files. Dynamic linking uses symbols in .dll files. Amr Ali Abdel-Naby@2011 Introduction to C Programming 165
166. Static vs. Dynamic Linking Static During compile time Linked symbols are added to executable. Larger executable No libraries’ dependencies on run time Library upgrade needs recompilation. Dynamic During run time Linked symbols are loaded from shared library. Smaller executable Depends on shared libraries location on run time. No recompilation needed Amr Ali Abdel-Naby@2011 Introduction to C Programming 166
167. Symbol Resolution Issues Symbols can be defined in multiple places. Suppose we define our own puts() function . But, puts() is defined in C standard library. Which puts compiler uses? Dynamic linking uses our puts as C standard library is known at run time only. Statically linking against C standard library causes an error. Amr Ali Abdel-Naby@2011 Introduction to C Programming 167
168. Outline Introduction to C Variables and Data Types Blocks and Compound Statements Control Flow Modular Programming Variable Scope I/O Pointers and Memory Addresses Arrays and Pointers Arithmetic Search and Sorting Algorithms User Defined Data Types Data Structures Callbacks Hash Tables Using External Libraries Creating Libraries Standard Library Amr Ali Abdel-Naby@2011 Introduction to C Programming 168
169. Standard Library <stdio.h> <ctype.h> <stdlib.h> <string.h> <assert.h> <stdarg.h> <time.h> … Amr Ali Abdel-Naby@2011 Introduction to C Programming 169
170. <stdio.h> fopen freopen fflush rename remove tmpfile tmpname fread fwrite fseek ftell rewind clearerr feof ferror Amr Ali Abdel-Naby@2011 Introduction to C Programming 170
171. <ctype.h> isalnum isctrl isdigit islower isprint ispunct isspace isupper Amr Ali Abdel-Naby@2011 Introduction to C Programming 171
175. <time.h> clock time difftime mktime asctime localtime ctime strftime Amr Ali Abdel-Naby@2011 Introduction to C Programming 175
176. Project II: BMP to JPEG Tool Amr Ali Abdel-Naby@2011 Introduction to C Programming 176 Required: Write a utility that converts a bmp image to a jpeg image. Deadline: A week from now References: http://en.wikipedia.org/wiki/BMP_file_format http://en.wikipedia.org/wiki/JPEG http://www.digicamsoft.com/itu/itu-t81-36.html http://www.cs.cf.ac.uk/Dave/Multimedia/node234.html http://www.w3.org/Graphics/JPEG/jfif3.pdf Bmp to jpeg utility
177. BMP File Format File header Image header Color table GAP1 Pixel array GAP2 Color profile Amr Ali Abdel-Naby@2011 Introduction to C Programming 177
178. BMP File Header Signature: 2 bytes “BM” File size: 4 bytes File size in bytes Reserved 1 and 2: Each 2 bytes Used by the image creator application File offset to pixel array: 4 bytes Offset from file start to pixel array Amr Ali Abdel-Naby@2011 Introduction to C Programming 178
179. BMP Image Header Each field is either 4 bytes or 2 bytes. Color space endpoints is 36 bytes. Planes must be 1. Bits per pixel can be 1, 4, 8, 16, 24, and 32. We will only focus on uncompressed bmp. Important color count is usually ignored. Masks can be used to extract data from pixels. Amr Ali Abdel-Naby@2011 Introduction to C Programming 179
180. BMP Color Table Mandatory when bits per pixel are less than 8. It defines colors used in the bitmap. Can be used to index bitmap images. A table entry is either 4 bytes or 3 bytes depending on the header version. Amr Ali Abdel-Naby@2011 Introduction to C Programming 180
181. BMP Pixels Amr Ali Abdel-Naby@2011 Introduction to C Programming 181
182. JPEG Compression Color space transformation Downsampling Discrete cosine transform Quantization Zigzag scanning DPCM on DC components RLE on AC components Entropy Coding Amr Ali Abdel-Naby@2011 Introduction to C Programming 182
183. Color Space Transformation and Downsampling Transforming RGB to YCbCr YCbCr allows reduction in Cb and Cr components. Downsampling Known Downsampling are: 4:4:4 4:2:2 4:2:0 Amr Ali Abdel-Naby@2011 Introduction to C Programming 183
184. Discrete Cosine Transform For 8×8 block, its values are shifted from a positive range to one centered around zero before computing the DCT. DCT is performed after shifting as follows: Amr Ali Abdel-Naby@2011 Introduction to C Programming 184
185. Quantization Dividing DCT output with quantization matrix. The output will is rounding of quantization. Amr Ali Abdel-Naby@2011 Introduction to C Programming 185
186. Zigzag Scanning Maps 8x8 matrix into a vector Amr Ali Abdel-Naby@2011 Introduction to C Programming 186
187. DPCM and RLE DPCM: Store the difference between the current DC value and the previous one RLE: Encode the AC values as pairs of (skip, value). Skip is the number of preceding zeroes. Value is the next non-zero value. (0,0) is used as end of block. Amr Ali Abdel-Naby@2011 Introduction to C Programming 187
188. Entropy Coding Categorize DC values into SSS Send off SSS as Huffman symbol, followed by actual 3 bits. For AC components (skip, value), encode the composite symbol (skip, SSS) using the Huffman coding. Huffman Tables can be custom (sent in header) or default. Amr Ali Abdel-Naby@2011 Introduction to C Programming 188
189. JPEG File Format Let’s check http://www.w3.org/Graphics/JPEG/jfif3.pdf Amr Ali Abdel-Naby@2011 Introduction to C Programming 189