Title: C Programming A Modern Approach
1C ProgrammingA Modern Approach
- K. N. King,
- C ProgrammingA Modern Approach,
- W. W. Norton Company, 1996.
2Note About Coverage
- This class has only part of the semester
dedicated to C - You already know Java, which has similar syntax
- You should be able to read the book quickly
3Similarities of C to Java
- / Comments /
- Variable declarations
- If / else statements
- For loops
- While loops
- Function definitions (like methods)?
- Main function starts program
4Differences between C and Java
- C does not have objects
- There are structures
- But data are not tied to methods
- C is a functional programming language
- C allows pointer manipulation
- Input / Output with C
- Output with printf function
- Input with scanf function
5C Strengths
- Efficiency
- Limited amount of memory
- Fast
- Portability
- Compilers are small and easily written
- C UNIX and ANSI/ISO standard
- Power
- Flexibility
- Standard library
- Input/output, string handling, storage
allocation, etc. - Integration with UNIX
6C Weakness
- Can be error-prone
- Flexibility
- C compiler doesnt detect many programming
mistakes - Pitfalls
- Can be difficult to understand
- Some features are easier to be misused
- Flexibility
- Can be difficult to modify
- No modules
7Compiling and Linking
8Variables and Assignments
- C is case-sensitive
- Compiler remembers only first 31 characters
- Type
- Should be declared
- int height, length, width
- Declarations must precede the statements.
- The value should be assigned before using the
variable in computations - height 8
- length 12
- width 5
- int volume height length width
9Constants
- Macro definition
- define SCALE_FACTOR (5.0/9.0)
- No semicolon at the end!
10Formatted Output printf
- printf(string, expr1, expr2,)
- Format string contains both ordinary characters
and conversion specifications - Conversion specification is a placeholder
representing a value to be filled in during
printing. - The information after specifies how the value
is converted form its internal form(binary) to
printed form (characters)
11(No Transcript)
12(No Transcript)
13Pitfalls
14(No Transcript)
15Formatted Input scanf
- scanf(string, expr1, expr2,)
- Reads input according to a particular format.
- Format string contains both ordinary characters
and conversion specifications - scanf(ddff, i, j, x, y)
- Number of conversion specification should match
number of variables. - Each conversion should be appropriate for type of
the variable. - while (scanf (d, i)1)
-
16How scanf Works
- For each conversion specification, tries to
locate an item of appropriate type, skipping
blank spaces if necessary. - Reads it, stopping when it encounters the symbol
that cant belong o item. - Ignores white-space characters.
- scanf(ddff, i, j, x, y)
-
17(No Transcript)
18Assignment Operators
- Simple assignment(right associative)
- int i5, j3
- int k 53
- i 72.99
- float f
- f 136
- i j k 7
- f i 33.3
- k 1 (j i)
- Compound assignments(right associative)
,
-, , /, - i j k
- i k vs i k
19Increment and Decrement Operators
- Prefix operators i, --i
- Postfix operators i, i
20Precedence and Associativity
21Sub expression Evaluation
- a 5
- c (b a 2) (a 1)
- i 2
- j i i
- Any expression can be used as a statement
- i
- ij -1
- i j / i j /
22Relational Operators
- 0 (false) and 1 (true)
- Their precedence is lower than the precedence of
the arithmetic operators. - Left associative
- i lt j lt k
-
23Equality Operators
- 0 (false) and 1 (true)
- Their precedence is lower than the precedence of
the relational operators. - i lt j j lt k
- Left associative
24Logical Operators
- Logical negation !
- !expr 1 if expr has the value 0
- Right associative
- The same precedence as unary plus and minus
- Logical and
- expr1 expr2 1 if both expr1 and expr2 has
non-zero values - Logical or
- expr1 expr2 1 if either expr1 or expr2 (or
both) has non-zero values - Short-circuit evaluation
- Left associative
- The precedence is lower that that of the
relational and equality operators
25if else Statement
- if (expression) statement
- if (expression) statement else statement
- Statement can be compound statements
- if (i0) vs if (i0)
- if (expression)
- statement
- else if (expression)
- statement
-
- else
- statement
26(No Transcript)
27Dangling else Problem
- if (y ! 0)
- if (x ! 0)
- result x / y
- else
- printf (Error y is equal to ) \n)
- Use compound statement
- Compiler always match the closest unmatched if
statement
28Conditional Expression
- expr1 ? expr2 expr3
- int i, j, k
- i 1
- j 2
- k i gt j ? i j
- k (i gt 0 ? i 0) j
- return (i gt j ? i j)
- printf (d\n, i gt j ? i j)
29 switch Statement
- switch ( expression )
- case constant-expression statements
-
- case constant-expression statements
- default statements
-
- Controlling expression should be an integer
expression (characters) - Constant expression cant contain variables or
function calls. - Statements do not require . Usually, the last
statement is break.
30Example
31while Loop
- while (expression) statement
- Statement can be compound
- while (igt0) printf (d\n, i--)
- while (igt0)
-
- printf (d\n, i)
- i--
-
- Infinite loops while(1)
- Break, goto, return
32Example
scanf(d, n)
33do Loop
- do statement while (expression)
- Statement can be compound
- do printf (d\n, i--) while (igt0)
- do
-
- printf (d\n, i)
- i--
- while (igt0)
34for Loop
- for (expr1 expr2 expr3) statement
- Statement can be compound
- expr1
- while (expr2)
- statement
- expr3
-
- for (i10 igt0 i--)
- printf (d\n, i)
- Infinite loop for ()
- Comma operator
- for (i1, j2 ijlt10 i, j) printf (d\n,
ij)
35Example
36Exiting From a Loop break
- for (d2 dltn d)
- if (nd0) break
- if (dltn) printf (d is divisible by d\n,
n,d) - else printf(d is prime \n,n)
- for ()
- printf (Enter a number(0 to stop) )
- scanf(d,n)
- if (n0) break
- printf(d cubed is d\n,n,nnn)
-
- break escapes only one level of nesting.
37Skipping the Rest of Iteration continue
- n 10
- sum 0
- while (n--gt0)
- scanf(d, i)
- if (i20) continue
- sumi
-
38Null statement
-
- for (d2 dltn d)
- if (nd0) break
- for (d2 dltn nd !0 d)
- Accidentally putting a semicolon after the
parentheses in if, while or for statement ends
the statement prematurely. - if (i0)
- printf (Zero\n)
- while (igt0) printf (d\n, i--)
39Basic Types Integers
- Signedness signed (defaut), unsigned
- Size short, long
- ltlimits.hgt holds ranges for int types.
40Integer Constants
- Decimal (base 10) literals
- digits between 0-9, no leading zero
- 15, 255, 32767
- Octal (base 8) literals
- digits between 0-7, must start with 0
- 017, 0377, 077777
- Hexadecimal (base 16) literals
- digits between 0-9 and letters between A-F (a-f),
must start with 0x (0X) - 0xF, 0xFF, 0x7FFF
41Basic Types Floating Types
- ltfloat.hgt
- Assume IEEE 754 standard
- Scientific notation sign, an exponent, a
fraction - .57e2, 57, 5.7e1, 570.0e-1
42Basic Types char
- Character set Latin (7 bit), ASCII (8 bit)
- Treats as integers
- unsigned (0-255) and signed (-128-127) version
- Some compilers use unsigned by default, the other
compilers use signed by default. - char ch65 / its A now /
- int i a / its 97 /
- ch / its B now /
- if (alt ch ch ltz)
- ch ch a A /
chtoupper(ch)/ - for (chA chltZ ch)
- cha b / c
43Read and Write char Alternative
- ch getchar()
- putchar(ch)
- while ( ( ch getchar() ) ! \n )
- while ((chgetchar()) )
- printf(Enter an integer )
- scanf(d, i)
- printf(Enter a command )
- command getchar()
44sizeof Operator
- sizeof (type-name)
- Unsigned integer representing the number of bytes
required to store a value of type-name - sizeof(char) is always 1
- Can be applied to constants, variables,
expressions - int i, j
- int k sizeof(i) / k is assigned 2/
- k sizeof (i j )
45Implicit Type Conversion
- Convert operands to the narrowest type that
will safely accommodate both values. - If the type of either operand is a floating
point - float -gt double - gt long double
- Otherwise
- if there are short and char operands,
convert them to int, then - int -gt unsigned int -gt long int -gt unsigned long
int - int i -10
- unsigned int u10
-
46Conversion During Assignment
- char c A
- int ind
- float f
- double d
- i c / will get 65 /
- f i / will get 65.0 /
- d f
- i 824.97 / 824 /
- c 100000000
- f 1.0e1000
47Explicit Type Conversion cast
- (type-name) expression
- Unary operator
- float f 3.45, frac
- frac f (int) f
- int num15, num2 3
- float quotient (float) num1/ num2
- int i1000
- long int i (long int) j j
- long int i (long int) (j j)
48Celsius vs Fahrenheit table (in steps of 20F)?
include ltstdio.hgt int main() int fahr,
celsius, lower, upper, step lower 0
upper 300 step 20 fahr lower
while (fahr lt upper) celsius 5 (fahr
- 32) / 9 printf("d\td\n",fahr,
celsius) fahr step return
1
- 5/9 0
- Integer arithmetic 0F 17C instead of 17.8C
- d, 3d, 6d etc for formatting integers
49New Version Using Float
include ltstdio.hgt int main() float
fahr, celsius int lower, upper, step
lower 0 upper 300 step 20
fahr lower while (fahr lt upper)
celsius (5.0 / 9.0) (fahr - 32.0)
printf("3.0f 6.2f \n", fahr, celsius)
fahr step return 1
- 6.2f 6 wide 2 after decimal
- 5.0/9.0 0.555556
- Float has 32 bits
- Double has 64 bits
- Long Double has 80 to 128 bits
- Depends on computer
50Version 3 with for loop
include ltstdio.hgt int main() int fahr
for (fahr0 fahr lt 300 fahr 20)?
printf("3d 6.1f \n", fahr, (5.0 /
9.0) (fahr 32.0)) return 1
51Version 4 with Symbolic Constants
include ltstdio.hgt define LOWER 0 define UPPER
300 define STEP 20 int main() int fahr
for (fahrLOWER fahr lt UPPER fahr STEP)?
printf("3d 6.1f \n", fahr, (5.0 /
9.0) (fahr - 32.0)) return 1
52One Dimensional Array
- Data structure containing a number of values of
the same type. - Declare array type, name and number of elements
- int a10
- Subscripting
- for (i0 iltN i) ai0
- for (i0 iltN i) scanf (d, ai)
- i0
- while (iltN)
- ai 0
- const int month31,28,31,30,31,30,31,31,30,31,3
0,31
53Array Initialization
- int a10 1,2,3,4,5,6,7
- int a 1,2,3,4,5,6,7
54sizeof Operator for Arrays
- sizeof(varName)
- Determines the size of variable in bytes.
- for ( i 0 ilt sizeof(a) / sizeof(a0) i)
- ai0
55Multidimensional Array
- int mij
- Stores in row-major order
- int m331,2,3,
- 4,5,6,
- 7,8,9
- int m331,2,4,5,6
56Arrays
- Count occurrences of each digit, blank, tab,
newline, other characters
include ltstdio.hgt int main() int c, i,
nwhite, nother int ndigit10 nwhite
nother 0 for (i0 ilt10 i)? ndigiti
0 while ((c getchar()) ! EOF)? if (c
gt '0' c lt '9')? ndigitc-'0'
else if (c ' ' c '\n' c '\t')?
nwhite else
nother
printf("digits ") for (i0 ilt10 i)?
printf("d ",ndigiti) printf(", white space
d, other d\n",nwhite, nother)
57Functions
- return type function-name (parameters)
-
- declarations
- statements
-
- Function can not return array
- If function doesnt return value, use void.
- List of parameters type name, type name (void)
- ex.float average(float a, float b) return
(ab)/2
58Function Calls
- A call of void function is a statement
- void f (int a)
- printf(d\n, a)
-
- f(345)
- A call of non-void function is an expression
- float average(float a, float b)
- return (ab)/2
-
- float av average (345, 2)
59Function Declaration
- C doesnt require to define function before its
first use. - void main()
- int i 4, k5
- float av average (i,k)
-
- float average(float a, float b) return
(ab)/2 - To ensure error message, declare function before
its first call (function prototype) - return-type function-name(parameters)
- float average (float a, float b)
- float average(float, float)
60Arguments
- Parameters appear in function definition
- Arguments are expressions in function calls.
- In C, arguments are passed by value
- int power (int x, int n)
- void main
- int k3, pow power (2, k)
-
- int power (int x, int n)
- int result1
- while (n-- gt0) resultx
- return result
-
61Example
- void decompose (float x, int integer, float
fract) - integer (int) x
- fract x integer
-
- void main()
- int i5
- float f 3.4
- decompose (3.14, i, f)
-
62Array Arguments
- int f (int a)
- int sum(int, int)
- int sum(int a, int n)
- int i,sum0
- for(i0 iltn i) sumai
- return sum
-
- int a101,4,6,7,3,2,4
- int total sum (a, 10)
- int f(int a10)
63return and exit Statements
- return expression
- double Largest (double x, double y)
- return xgty? x y
-
- void print_int(int i)
- if (ilt0) return
- printf(d\n,i)
-
- The value returned by main is a status code.
- In ltstdlib.hgt exit(expression)
- Normal success EXIT_SUCCESS (0)
- Abnormal termination EXIT_FAILURE (1)
64Recursive Function
- int power (int x, int n)
- return n0? 1 xpower(x, n-1)
-
- int factorial(int n)
- return nlt1 ? 1 nfactorial(n-1)
-
- int sum_digits(int n)
- return n0 ? 0 n10sum_digits(n/10)
-
-
65Functions
include ltstdio.hgt int power(int, int)
/ function prototype / int main() int i
for (i 0 i lt 10 i)? printf("d d
d\n", i, power(2,i), power(-3,i)) int
power(int base, int n) int p for (p 1 n
gt 0 --n)? p p base return p
66Functions
- Call by value mechanism
- Change in n's value not reflected in main
- Using pointers, we can achieve Call by reference
effect.
67External (Global) Variables
- All variables declared so far are local to the
functions - External or Global variables are accessible to
all functions - These are defined once outside of functions
- Must be defined once more within each function
which is going to use them
68Scope Rules
- Automatic/Local Variables
- Declared at the beginning of functions
- Scope is the function body
- External/Global Variables
- Declared outside functions
- Scope is from the point where they are declared
until end of file (unless prefixed by extern)?
69Scope Rules
- Static Variables use static prefix on functions
and variable declarations to limit scope - static prefix on external variables will limit
scope to the rest of the source file (not
accessible in other files)? - static prefix on functions will make them
invisible to other files - static prefix on internal variables will create
permanent private storage retained even upon
function exit
70Example
- int i //global variable
- void f1 ()
-
- int j0 //call every time when f invoked
- j
void f2 () static int j0 //only done once
j
71Scope Rules
- Variables can be declared within blocks too
- scope is until end of the block
72Data Structures (struct)
- Arrays require that all elements be of the same
data type. - C and C support data structures that can store
combinations of character, integer floating point
and enumerated type data. They are called a
structs.
73Structures (struct)
- A struct is a derived data type composed of
members that are each fundamental or derived data
types. - A single struct would store the data for one
object. An array of structs would store the data
for several objects. - A struct can be defined in several ways as
illustrated in the following examples -
74Declaring Structures (struct)
struct date int day char
month3 char year4 / The name date"
is called a structure tag / Struct date
date1 Struct date date2 3,Jan,1912
- Struct
-
- int day
- char month3
- char year4
- my_date
-
- my_date date3 2,Jul,2010
75User Defined Data Types (typedef)
- The C language provides a facility called typedef
for creating synonyms for previously defined data
type names. For example, the declaration -
- typedef int Length
- makes the name Length a synonym (or alias)
for the data type int. - The data type name Length can now be used in
declarations in exactly the same way that the
data type int can be used - Length a, b, len
- Length numbers10
76Typedef Struct
- Often, typedef is used in combination with struct
to declare a synonym (or an alias) for a
structure -
- typedef struct / Define a structure /
-
- int label
- char letter
- char name20
- Some_name / The "alias" is Some_name /
-
- Some_name mystruct / Create a struct
variable /
77Accessing Struct Members
- Individual members of a struct variable may be
accessed using the structure member operator (the
dot, .) - mystruct.letter
-
- Or , if a pointer to the struct has been declared
and initialized - Some_name myptr mystruct
- by using the structure pointer operator (the
-gt) - myptr -gt letter
- which could also be written as
- (myptr).letter
78Sample Program With Structs
- int main ( )
-
- struct identity js "Joe Smith", ptr js
- js.person.id 123456789
- js.person.gpa 3.4
- printf ("s ld f\n", js.name, js.person.id,
- js.person.gpa)
- printf ("s ld f\n", ptr-gtname,
ptr-gtperson.id, - ptr-gtperson.gpa)
-
/ This program illustrates creating structs and
then declaring and using struct variables. Note
that struct personal is an included data type in
struct "identity".
/ include ltstdio.hgt struct
personal //Create a struct long
id float gpa struct identity
//Create a second struct that includes the first
one. char name30 struct
personal person
79Enumeration enum
- enum is a type whose values are listed
(enumerated) by the programmer who creates a name
(enumeration constant) for each of the values. - enum yellow,red, green, blue c1,c2
- enum colors yellow,red, green, blue
- enum colors c1,c2
- typedef enum yellow,red, green, blue Colors
- Colors c1,c2
- typedef enum FALSE, TRUE Bool
- C treats enumeration variables and constants as
integers.
80- include ltstdio.hgt
- int main( )
-
- int apr570,0,0,0,1,2,3,4,5,6,7,8,9,10,
- 11,12,1314,15,16,17,18,19,20,21,22,23,24,
- 25,26,27,28,29,30
- enum days Sunday, Monday, Tuesday,
- Wednesday, Thursday, Friday, Saturday
- enum week week_1, week_2, week_3,
- week_4, week_5
- printf ("Monday at the third week of April is
- April d\n, apr week_3 Monday )
-
81enum
- enum dept CS20, MATH10, STAT25
- enum colors BLACK, GRAY7, DK_GRAY, WHITE15 c
- int iGRAY /its 7 now/
- c0 /its BLACK
now/ - c8 /its DK_GRAY
now/ - i c4 2 / its 16 now /
- typedef struct
- enum RANK, DEG kind
- union status
- int rank
- char deg4 status
82Pointers
- Executable program consists of both code and
data. - Each variable occupies one or more bytes of
memory - The address of the first byte is said to be the
address of the variable. - Pointer variable is a variable storing address.
- int i1
- int p i
- Declaration
- type name
- int i, j, p
p
1
i
2000
83The Address and Indirection operators
- operator returns address of a variable
- int i, p
- p i
- int i, pi
- p is alias for i.
- i1 p2
- operator returns an object that a pointer
points to. - printf(d\n, p)
- int jI
84Pointer Assignment
- int x ,y, p, q
- p x
- q y
- qp
- p 1
- q 2
- int x1, y2, p, q
- p x
- q y
- p q
-
85Pointers as Argument
- void decompose (float x, int integer, float
fract) - integer (int) x
- fract x integer
- void main()
- int i5 float f 3.4
- decompose (3.14, i, f)
- scanf(d, i)
- p i
- scanf(d, p)
86const to Protect Arguments
- void f(const int p)
- int j
- pj
- p1
- void f(int const p)
- int j
- pj
- p1
- void f(const int const p)
- int j
- pj
- p1
87Pointers as Return Values
- double Largest (double x, double y)
- return xgty? x y
-
- int p, x,y
- p max(x, y)
- You can return pointer to one element of the
array passed as an argument, to static local
variable, to external variable. - Never return a pointer to an automatic local
variable!
88Pointer Arithmetic
- int a5, pa0
- pa
- int q
- pa2
- qp2
- p
89Pointer Arithmetic
90Pointer Arithmetic
- int a5
- int qa1, pa4
- int ip-q
- iq-p
- Meaningful, if pointers point to the element of
the same array. - pltq
- int sum0
- for (pa0pltaN p)
- sump
91Combining and (--)
- int sum0, pa0
- while (pltaN)
- sump
92Array Name as a Pointer
- int a10, pa
- a 7
- (a1)12
- (ai) is the same as ai
- pi is the same as (pi)
- for (pa pltaN p) sump
- Array parameter is treated as pointer, so its
not protected against change. - The time required to pass array to a function
doesnt depend on its size. - int f(int a) is the same as int f(int a)
- int max f(a5,10)
93Pointer Example
cat ptr_example.c include ltstdio.hgt int
main() int x1 int p / p points to
an integer / p x / Set p to x's
address / printf(" x is d\n", x) p
0 / Set p's value to 0 / printf(" x now
is d\n", x) return 0 gcc
ptr_example.c -o ptr_example ./ptr_example x
is 1 x now is 0
94Using pointers to achieve Call-By-Reference effect
- Pass the address of a variable
- Alter the value
void swap (int px, int py) int temp
temp px px py py temp
int a10,b20 swap(a,b)
95Main difference between arrays and pointers
- Even though both contain addresses
- Array name is not a variable so
- pa a pa OK
- a pa a NOT OK
- When an array name is passed as a parameter to a
function - Actually the address of the first element is
passed - Arrays are always passed as pointers
96Strings
- Double quotes
- C treats string literals as character arrays,
that is, a pointer of type char . - For string literal of length n, it stores n
characters of the string literal and null
character (\0) to mask the end of the string. - char ch abc1
- char digit_to_hex(int digit)
- return 0123456789ABCDEFdigit
-
- char pabc
- pb / not recommended/
97String Variables
- char strlength1
- char date8June 14
- char date9June 14 /2 null characters at
the end/ - char dateJune 14
- char dtJune 14
- Characters of array date can be modified, dt
points to string literal which characters should
not be modified. - date is an array name, dt is a pointer and can
point to the other string literal. - char strlength1, p
- pstr
98Writing Strings
- printf(s\n,str)
- printf(.4s\n,C is a fun language)
- printf(10s\n,Hi)
- printf(10.4s\n,C is a fun language)
- puts(str)
99Reading Strings
- scanf(s, str) / never contain white spaces/
- scanf(10s, str)
- gets(str)
- Reads until finds newline character
- It replaces newline character with null character
before storing to a variable - Doesnt skip leading white spaces
100C String Library
- char str110,str210
- str1abc /wrong/
- str2str1 /wrong/
- str1str2 compares pointers!
- ltstring.hgt
- char strcpy(char s1, const char s2)
- strcpy(str2, abcd)
- strcpy(str1,strcpy(str2, abcd))
101C String Library
- char strcat(char s1, const char s2)
- strcat(str1, abc) strcat(str2, def)
- strcat(str1, strcat(str2,gi))
- int strcmp(const char s1, const char s2)
- Lexicographic ordering
- if (strcmp(str1,str2)lt0)
- size_t strlen(const char s)
- int len strlen(abc)
- len strlen()
102String Idiom
- Search for the null character at the end of a
string - while(s) s
- while(s)
- size_t strlen(const char s)
- const char ps
- while (s)
- return s-p
-
103Dynamic Storage Allocation
- Its ability to allocate storage during program
execution - Available for all types of data
- Mostly used for strings, arrays and structures.
- Dynamically allocated structures can form lists,
trees and other data structures. - ltstdlib.hgt
- malloc allocates a block of memory, but doesnt
initialize it - calloc allocates a block of memory and clears it
- free releases the specified block of memory
104NULL Pointer
- If memory allocation function cant allocate a
block of the requested size, it returns a null
pointer (NULL). - ltlocale.hgt,ltstddef.hgt,ltstdio.hgt,ltstdlib.hgt,
ltstring.hgt, lttime.hgt - It is responsibility of a programmer to test if
received pointer is a null pointer. - pmalloc(1000)
- if (pNULL) / appropriate actions/
- if ((pmalloc(1000))NULL) /actions/
- if (p) . is the same as if (p!NULL)
- if (!p) . is the same as if (pNULL)
105Using malloc Strings
- void malloc(size_t size)
- Allocates a block of size bytes and returns a
pointer to it if fails, returns NULL. - Since sizeof(char) is1, to allocate space for a
string of n characters - char pmalloc(n1)
- Memory allocated using malloc isnt cleared or
initialized strcpy(p, abc) - There are no checks to detect usage of memory
outside the bounds of the block - Dynamical allocation makes possible to write
functions that return a pointer to a new
string char p
concat(abc,def)
106- includeltstring.hgt
- includeltstdlib.hgt
- includeltstdio.hgt
- char concat(const char s1, const char s2 )
- char resultmalloc(strlen(s1)strlen(s2)1)
- if (resultNULL)
- printf(malloc failed\n)
- exit(EXIT_FAILURE)
-
- strcpy(result,s1)
- strcpy(result,s2)
- return result
107Dynamically Allocated Arrays
- Elements of an array can be longer than one byte
gt sizeof should be used. - int amalloc(n sizeof (int))
- for(i0iltni) ai0
- void calloc(size_t nmemb, size_t size)
- Allocates space for an array with nmemb elements,
each of which is size bytes sets all bits to 0
and returns a pointer to it. - If space is not available, returns NULL.
- int acalloc(n, sizeof(int))
- struct point int x,y p
- pcalloc(1, sizeof(struct point))
108Deallocating Storage
- Memory block are obtained from a storage pool
(heap). - Garbage is a block of memory thats no longer
accessible to a program. - A program that leaves garbage behind has a memory
leak. - int pmalloc(100), qmalloc(100)
- pq
- void free (void ptr)
- int pmalloc(100), qmalloc(100)
- free(p)
- pq
109Memory Leak Examples
- int int_ptr
- for ()
- int_ptr malloc(100 sizeof(int) )
- if ( int_ptr NULL )
- fprintf(stderr, "...")
- exit(1)
-
-
- for ( i 1 i lt 5 i)
- printf("s\n", concat(abc,
012345digit))
110Memory Leak
- for ( i 1 i lt 5 i)
- char strconcat(abc, 012345digit)
- printf("s\n", str)
- free(str)
-
- for ( i 1 i lt 5 i)
- char strconcat(abc, 012345digit)
- free(str)
- printf("s\n", str)
- free(str)
111Dangling Pointers
- char pmalloc(4)
-
- free(p)
-
- strcpy(p,abc) /wrong/
- Several pointers may point to the same block of
memory. When the block is freed, all these
pointers are left dangling.
112Memory Allocation Rules
- If memory is allocated it must be freed.
- Do not use memory after it is freed.
- Do not free memory that will be used later.
- Do not free a block of memory more than once.
- Do not free memory that was not allocated.
- Do not use memory outside the bounds of an
allocated block.
113Linked Lists
- A linked list is a chain of structures (nodes),
with each node containing a pointer to the next
node in the chain. - The last node in the list contains a null pointer.
114Declaring a Node Type
- struct node
- int value
- struct node next
-
- struct point
- double x,y
-
- struct vertex
- struct point element
- struct vertex next
115Building Linked List
- First, create an empty list
- struct node firstNULL
- Then create nodes one by one
- Allocate memory for the node
- struct node new_node
- new_nodemalloc(sizeof (struct node))
- Store data into the node
- (new_node).value10
- new_node-gtvalue10
- Insert the node into the list
116Inserting a Node at the Beginning of the List
- If first points to the first node of the linked
list - new_node-gtnextfirst
- firstnew_node
struct node firstNULL, new_node
new_node
new_nodemalloc(sizeof (struct node))
117Inserting a Node at the Beginning of the List
new_node-gtvalue10
new_node-gtnextfirst
firstnew_node
118Inserting a Node at the Beginning of the List
new_nodemalloc(sizeof (struct node))
new_node-gtvalue20
new_node-gtnextfirst
firstnew_node
119Searching a Linked List
- for (pfirst p!NULL pp-gtnext)
-
- int value20 struct node p
- for (pfirst p!NULL pp-gtnext)
- if (p-gtvalue value) return p
- struct node find(struct node list, int n)
- while (list!NULL and list-gtvalue!n )
- pp-gtnext
- return list
first
20
10
120Inserting a Node at the Middle of the List
- struct node pfirst
- struct node cur find(p, 10)
- struct node tmp malloc(sizeof (struct node))
- tmp-gtvalue cur-gtvalue
- tmp-gtnext cur-gtnext_ptr
- cur-gtvalue 15
- cur-gtnext tmp
121Deleting a Node from the List
- struct node pfirst
- struct node cur find(p, 20)
- struct node tmp
- tmp cur-gtnext
122Review
- C versus Java
- C data types
- Functions
- Control Flow
- Scope
- Pointers, Arrays
- Strings