Download presentation
Presentation is loading. Please wait.
1
The C Programming Language
Currently one of the most commonly-used programming languages “High-level assembly” Small but powerful Very portable:compiler exists for virtually every processor
2
Hello World in C #include <stdio.h> int main() {
Include a header file that lets you use I/O related C functions Similar to Java’s import #include <stdio.h> int main() { printf(“Hello, world!\n”); return 0; }
3
Why is C Dangerous C’s small feature set is an advantage and disadvantage The price of C’s flexibility C does not, in general, try to protect a programmer from his/her mistakes
4
Commonly used header files
stdio.h Standard C library for I/O stdlib.h General purpose standard C library string.h math.h sqrt, pow, sin, cos ctype.h a bunch of very useful character functions: isdigit, isalpha, isalnum, isspace, islower, isupper, tolower/toupper time.h
5
Hello World in C #include <stdio.h> int main() {
Program mostly a collection of functions “main” function special: the entry point “int” qualifier indicates function returns an integer #include <stdio.h> int main() { printf(“Hello, world!\n”); return 0; } I/O performed by a library function
6
C is Function-oriented
C came before OO concept C program resemble java programs with a single giant class C is procedural Program organization and modularization is achieved through function design Carefully plan your function return type and parameter list Write small functions!
7
Functions Function: Unit of operation Must have the main function
CSE123 Lec02 Functions Function: Unit of operation A series of statements grouped together Must have the main function C functions are stand-alone Most programs contain multiple function definitions Must be declared/defined before being used
8
Functions int menuChoice() { int choice; printf( "1. Yes\n" "0. No\n"
CSE123 Lec02 Functions int menuChoice() { int choice; printf( "1. Yes\n" "0. No\n" "Enter the number corresponding to your choice: "); scanf("%d", &choice); return choice; } int main() { printf("=== Expert System ===\n"); printf("Question1: ...\n"); choice = menuChoice(); if (choice == 1) { /* yes */ printf("Question 2: ...\n"); /* skipped */ getA() getB() getC()
9
Function parameters void km_mile_conv(int choice) { int input;
CSE123 Lec02 Function parameters void km_mile_conv(int choice) { int input; printf("Enter a %s value: ", choice==1?"mile":"km"); scanf("%lf", &input); if (choice == 1) printf("%f mile(s) = %f km(s)\n", input, input*1.6); else printf("%f km(s) = %f mile(s)\n", input, input/1.6); } int main() { int choice; scanf("%d", &choice); switch (choice) { case 1: km_mile_conv(choice); break; caea 2: /* more cases */
10
Function Return and Parameters
CSE123 Lec02 Function Return and Parameters The syntax for C functions is the same as Java methods void keyword can be omitted void km_to_mile(void) { } mile_to_km() { int main() { int choice; Function in C is more general than the math counterpart. But, still closely related For now, return type int and double Only one value NOTE: C compiler doesn't check this! just return would be allowed as well
11
CSE123 Lec02 Function Prototype A prototype is a function declaration which includes the return type and a list of parameters A way to move function definitions after main Need not name formal parameters /* function prototypes */ double km2mile(double); double mile2km(double); int main() { } /* actual function definitions */ double km2mile(double k) { double mile2km(double m) { Summary; Questions Try to define functions: Applicable cases in homeworks?
12
Function name overloading
Does not exist in C Exists in C++
13
Local/Global Variables
CSE123 Lec02 Local/Global Variables Variables declared inside a function are local Function arguments are local to the function passed to A global variable is a variable declared outside of any function. In a name conflict, the local variable takes precedence When local variable shadows function parameter? int x = 0; int f(int x) { int x = 1; return x; } int main() { int x; x = f(2); There are cases where we want to use non-local variables. Let's look at local vars more in detail.
14
Scope of Global Variables
The scope of a global variable starts at the point of its definition. Globals should be used with caution If using globals at all, declare them at the top. int x; int f() { } int y; int g(){ int main() {
15
Keep main Uncluttered Your main function should consist mainly of function calls One main input loop or conditional is okay Write your main and choose your function name in such a way so that the main algorithm and program structure is clearly represented the reader can get an idea how your program works simply by glancing at your main
16
Program Organization #include and #define first Globals if any
Function prototypes, unless included with header file already int main()– putting your main before all other functions makes it easier to read The rest of your function definitions
17
Data Types Integer types: different number of bits-different ranges
CSE123 Lec02 Data Types Integer types: different number of bits-different ranges char: ASCII character, typically 8 bits=1 byte range –127 to 128 short: typically 16 bits int: 32 bits range ±2 billion long: typically 32 bits long long: (some compilers support) 64-bits Integer types can be preceded by unsigned which disables representing negative numbers e.g. unsigned char range 0-255 Omission of ‘f’ may cause warning (depending on how the value is used) Can be omitted in initialization Otherwise, warning will be issued
18
Data Types Floating-point types float 4 bytes double 8 bytes
CSE123 Lec02 Data Types Floating-point types float 4 bytes double 8 bytes long double 12 bytes Floating point constants default to double unless suffixed by f or l Examples: 0.67f, f, 1.2E-6f, 0.67, Omission of ‘f’ may cause warning (depending on how the value is used) Can be omitted in initialization Otherwise, warning will be issued
19
Boolean C does not have type boolean—use int False is represented by 0
Any expression evaluates to non-zero is considered true True is typically represented by 1 however
20
Constants Integer Floating point number
const int year = 2002; Floating point number const double pi = ; Constants are variables whose initial value can not be changed. Comparable to static final
21
#define Often used to define constants
#define TRUE 1 #define FALSE 0 #define PI 3.14 #define SIZE 20 Anywhere PI occurs compiler replaces with 3.14 Offers easy one-touch change of scale/size #define vs const The preprocessor directive uses no memory
22
Types and Casting Choose types carefully
An arithmetic operation requires that the two values are of the same type For an expression that involves two different types, the compiler will cast the smaller type to the larger type Example: 4 * 1.5 = 6.0
23
Mixing Data Types int values only int
CSE123 Lec02 Mixing Data Types int values only int 4 / 2 2 3 / 2 1 int x = 3, y = 2; x / y 1 Involving a double value double 3.0 / 2 1.5
24
sizeof and Type Conversions
sizeof(type) The sizeof operator returns the number of bytes required to store the given type Implicit conversions arithmetic assignment function parameters function return type Explicit conversions casting int x; x = (int) 4.0;
25
Use of char (character)
CSE123 Lec02 Use of char (character) Basic operations Declaration: char c; Assignment: c = 'a'; Reference: c = c + 1; Constants Single-quoted character (only one) Some special characters: '\n‘ (newline), '\t' (tab), '\"' (double quote), '\'' (single quote), '\\' (backslash) Example '0' vs. 0
26
Characters are Integers
A char type represents an integer value A single quoted character is called a “character constant”. C characters use ASCII representation: 'A' = 65 … 'Z' = 'A' + 25 = 90 'a' = 97 … 'z' = 'a' + 25 = 122 '0'!= 0 (48), '9' - '0' = 9 Never make assumptions of char values Always write 'A' instead of 65
27
ASCII Table American Standard Code for Information Interchange
CSE123 Lec02 ASCII Table American Standard Code for Information Interchange A standard way of representing the alphabet, numbers, and symbols (in computers) Correspondence Character - Decimal number - Binary number How to distinguish binary vs. decimal? => subscript How to distinguish character vs. number? => type Summarize; Questions? Decimal = base-10 Binary = base-2 Hexadecimal = base-16 Arbitrary base-k: exercise: 123 in base 4?
28
Output Functions Output characters Output an integer
CSE123 Lec02 Output Functions Output characters printf("Text message\n"); Output an integer int x = 100; printf("Value = %d\n", x); \n for new line Text uses %d => same %i seems easier to remember Output: Value = 100
29
Variations Output a floating-point number Output multiple numbers
CSE123 Lec02 Variations Output a floating-point number double y = 1.23; printf("Value = %f\n", y); Output multiple numbers int x = 100; printf("x = %d, y = %f\n", x, y); 15 digits below decimal (excluding trailing 0’s) Using wrong types What-about questions Encouraged Try them yourself Some homework problems involve these Output: x = 100, y =
30
printf Summary printf(" ", ); Text containing special symbols
CSE123 Lec02 printf Summary printf(" ", ); Text containing special symbols %d for an integer %f for a floating-point number \n for a newline List of variables (or expressions) In the order correspoding to the % sequence More in text Section 3.1
31
% Specification %s string pointed by a char* (most commonly used ones)
CSE123 Lec02 % Specification (most commonly used ones) %c convert an int to an unsigned char and print as a character %i int, char (printas a signed decimal number) %d same as above (d for decimal) %f float, double (floating-point) %e float, double (exponential, e.g., 1.5e3) %s string pointed by a char*
32
Formatting Precision %.#f Width %#f, %#d
CSE123 Lec02 Formatting Precision %.#f Width %#f, %#d Note: Entire width Various combinations of the above and other options available Replace # with digit(s)
33
Formatting Example %f with 1.23456789 >1.234568<
CSE123 Lec02 Formatting Example %f with > < %.10f with > < %.2f with >1.23< %d with >12345< %10d with > < %2d with >12345< %8.2f with > <
34
char Input/Output Input Output
CSE123 Lec02 char Input/Output Input char getchar() receives/returns a character Built-in function Output printf with %c specification putchar() We will mostly use a way to input a series of characters rather than a single character int main() { char c; c = getchar(); printf("Character >%c< has the value %d.\n", c, c); return 0; }
35
scanf Function scanf(" ", ); Format string containing special symbols
CSE123 Lec02 scanf Function scanf(" ", ); Format string containing special symbols %d for int %f for float %lf for double %c for char \n for a newline List of variables (or expressions) In the order correspoding to the % sequence More in text Section 3.1
36
scanf Function The function scanf is the input analog of printf
CSE123 Lec02 scanf Function The function scanf is the input analog of printf Each variable in the list MUST be prefixed with an &. Ignores white spaces unless format string contains %c Schematic
37
scanf Function int main() { int x; printf("Enter a value:\n");
CSE123 Lec02 scanf Function int main() { int x; printf("Enter a value:\n"); scanf("%d", &x); printf("The value is %d.\n", x); return 0; } Schematic
38
scanf with multiple variables
CSE123 Lec02 scanf with multiple variables int main() { int x; char c; printf("Enter an int and a char:"); scanf("%d %c", &x, &c); printf("The values are %d, %c.\n", x, c); return 0; } Schematic
39
Control Structures Conditionals Loops SAME syntax as in Java if-else
switch Loops while for do-while SAME syntax as in Java
40
Assignment as Expression
CSE123 Lec02 Assignment as Expression Assignment Assignments are expressions Evaluates to value being assigned Example int x = 1, y = 2, z = 3; x = (y = z); One of most common errors if (x = 1) C compiler won’t display error messages evaluates to 3 (true) if (x = 3) { ... } evaluates to 3
41
Complex Data Types Pointers Arrays Strings Structures
42
Variable and Address Variable = Storage in computer memory
CSE123 Lec02 Variable and Address Variable = Storage in computer memory Contains some value Must reside at a specific location called address Basic unit – byte Imagine memory as a one-dimensional array with addresses as byte indices A variable consists of one or more bytes, depending on its type (size) Memory 70 31 4 6 30 1 10 95 201 12 2 3 5 7 8 9 address value char int Examples Value at address 7: 4 Value at address 30: 45 In C program, they may be called: x, i, etc. Every variable has an address where it is located. Use of variable name for int, double, char In declaration: allocation In expression: reference LHS of an assignment: store the RHS value to that variable => constant on LHS does not make sense
43
Pointer – Reference A pointer (pointer variable) is a variable that stores an address (like Java reference) Recall in Java, when one declares variables of a class type, these are automatically references. In C, pointers have special syntax and much greater flexibility.
44
Address Operations in C
CSE123 Lec02 Address Operations in C Declaration of pointer variables The pointer declarator ‘*’ Use of pointers The address of operator ‘&’ The indirection operator ‘*’ – also known as de-referencing a pointer C representation in your program
45
Pointer Declaration Syntax Must be declared with its associated type.
CSE123 Lec02 Pointer Declaration Syntax destinationType * varName; Must be declared with its associated type. Examples int *ptr1; A pointer to an int variable char *ptr2; A pointer to a char variable ptr1 ptr2 will contain addresses
46
Pointers are NOT integers
Although memory addresses are essentially very large integers, pointers and integers are not interchangeable. Pointers are not of the same type A pointer’s type depends on what it points to int *p1; char *p2;
47
Address of operator int i = 8; int *ip; ip = &i; 0012FF88 8 ip
48
CSE123 Lec02 Pointer Assignment A pointer p points to x if x’s address is stored in p Example int x = 1; int *p, *q; p = &x; q = p; Interpreted as: x 1 address = 567 p 567 q 567 p x 1 q
49
Pointer Assignment Example int x=1, y=2, *p, *q; p = &x; q = &y;
CSE123 Lec02 Pointer Assignment Example int x=1, y=2, *p, *q; p = &x; q = &y; q = p; x 1 y 2 address = 567 address = 988 p 567 q 988 567
50
Indirection Operator Syntax Example * pointerVar
CSE123 Lec02 Indirection Operator Note: ‘*’ in a declaration and ‘*’ in an expression are different. int *p; int * p; int* p; Syntax * pointerVar Allows access to value of memory being pointed to Also called dereferencing Example int x = 1, *p; p = &x; printf("%d\n", *p); *p refers to x; thus prints 1 p x 1
51
Assignment Using Indirection Operator
CSE123 Lec02 Assignment Using Indirection Operator Allows access to a variable indirectly through a pointer pointed to it. Example int x = 1, *p; p = &x; *p = 2; printf("%d\n", x); *p is equivalent to x p x 1 Schematic next p x 2
52
The NULL Pointer A pointer that contains the address zero known as the NULL pointer It points to nothing Many of the standard header files define NULL NULL means false in conditions int *ip; if (ip) { /* ip is not NULL */ }
53
Pointer initialization
DO NOT derefence an undefined/unitialized pointer! It could be pointing anywhere.
54
CSE123 Lec02 Pass by Value Same as Java, modification to function arguments during function execution has no effect outside of function void f(int x) { x = x * x; printf("%d", x); } int main() { int x = 3; f(x); return 0; The variable x in f gets a copy of the value of the variable x in main. Summarize: Local variables Local scope Flexible name use Convenient for modularity Question? Does not change the value of x in main.
55
Pass by Value and Pointers
All functions are pass-by-value in C Pass-by-value sill holds even if the parameter is a pointer A copy of the pointer’s value is made – the address stored in the pointer variable The copy is then a pointer pointing to the same object as the original parameter Thus modifications via de-referencing the copy STAYS.
56
Function Arguments x and y are copies of the original, and thus a and b can not be altered. void swap(int x, int y) { int tmp; tmp = x; x = y; y = tmp; } int main() { int a = 1, b = 2; swap(a, b); return 0; Wrong!
57
Pointers and Function Arguments
Passing pointers – a and b are passed by reference (the pointers themselves px and py are still passed by value) void swap(int *px, int *py) { int tmp; tmp = *px; *px = *py; *py = tmp; } int main() { int a = 1, b = 2; swap(&a, &b); return 0; px py a 1 b 2
58
pointers to pointers int i; int *ip = &i;
int **iip = &ip; /* iip points to ip */ ….
59
Generic pointers Sometimes necessary to store or pass pointers without knowing what type they refer to—use the generic pointer type: void * int x; int *xp = &x; void *vp = xp; /*okay, types are compatible*/ float *fp = ip; /*error */ BUT, a generic pointer cannot be derefenced: x = *vp; /*error */
60
Arrays Declaration – int a[5]; Assignment – a[0] = 1;
CSE123 Lec02 Arrays Declaration – int a[5]; Allocates a static array Assignment – a[0] = 1; Reference – y = a[0]; a ? a 4 ? 1 element 1 2 k2 k1 index
61
CSE123 Lec02 Pointers and Arrays Arrays are contiguous allocations of memory of the size: sizeof(elementType) * numberOfElements Given the address of the first byte, using the type (size) of the elements one can calculate addresses to access other elements pointer Memory 70 31 4 6 30 1 10 45 12 2 3 5 7 8 9 address value 1 array Back: Schematic for longSentence Convinced of the importance of pointers? Suppose you see an E on for CSE110 Suppose a group of gang members looking at a photo Summary; Questions Pointers: a variable contains an address; can manipulate information at another location
62
Name of an Array The variable name of an array is also a pointer to its first element. a == &a[0] a[0] == *a a a+1 a+8 a: a[0] a[1] a[8]
63
Pointer Arithmetic One can add/subtract an integer to/from a pointer
The pointer advances/retreats by that number of elements (of the type being pointed to) a+i == &a[i] a[i] == *(a+i) Subtracting two pointers yields the number of elements between them
64
Array name is a constant pointer
int arr[5]; int x; int *s = &x; arr = s; /*illegal */
65
Arrays as Arguments Arrays are passed by reference Modifications stay
CSE123 Lec02 Arrays as Arguments Arrays are passed by reference Modifications stay #define SIZE 10 void init(int a[]) { int i; for(i = 0;i<SIZE;i++){ a[i] = 0; } int main() { int a[SIZE]; init(a); return 0; /* equivalent pointer alternative */ void init(int *a) { int i; for(i = 0;i<SIZE;i++){ *(a+i) = 0; } Want to know array argument real well? Schematic Facts Use of array name as an expression (e.g., when passing) corresponds to passing the address of the array Use of array name with [] is equivalent to allocating a pointer argument => index optional; ignored How to know array size? Strings: check ‘\0’ Non-string: supply the size in some way (constant, argument)
66
Character and String String is not a special type Null character
CSE123 Lec02 Character and String String is not a special type An array of characters Terminated with a special, null character Null character Its integer value is 0. Its C representation is '\0'. E.g., "abc" is internally '\0' '0' (zero) '\0' '\n' 'a' 'b' 'c' '\0'
67
Example 'O' 'o' '0' '\0' Values: 79 111 48 0 Big-O Little-o Zero
CSE123 Lec02 Example Big-O Little-o Zero Null character 'O' 'o' '0' '\0' Values:
68
Declaration/Initialization
CSE123 Lec02 Declaration/Initialization Declaration: char s[5]; Initialization: char t[] = "abc"; char *s = t; Note: Strings cannot be assigned using '=' (except initialization). Schematic Declaration (no initialization) Initialization = array declaration (automatic size) Use of double quotes, cf. single quote for a character 14-foreignNames.c void main() { char name[200]; /* then #define BUFLEN 200 */ } Summarize; Questions Two properties of string Would array operations sufficient for string processing? Yes => but specialized ops convenient due to null termination Left (enough space below)
69
String Output Use printf with the %s specification
CSE123 Lec02 String Output Use printf with the %s specification Prints character elements until \0 is reached char s[] = "abc"; printf("%s", s); /* prints abc */ printf("string: >%s<", s); /* prints string: >abc< */ String name = array name => array argument But no modification
70
CSE123 Lec02 printf and Strings int main() { char s[] = "01234"; char *p; p = s; printf("%s\n", s); printf("%s\n", p+1); } %s: Displays characters from the specified address until '\0' Further analysis of array notations in connection to pointer operations %d, %f, %c => value; %s => pointer Schematic
71
String Input with scanf
CSE123 Lec02 String Input with scanf Use the scanf function with %s Matches the input string up to the first white space or '\n' and stores it into buf Given input "CSE 123\n" scanf %s will have stored "CSE" Input buffer after scanf call: "123\n" No need for & in front of buf scanf("%s", buf); Array argument => array elements can be modified => input Schematic: Array will be modified 14-foreignNames.c #define BUFLEN 200 void main() { char name[BUFLEN]; printf("Name? "); gets(name); printf("Entered: %s\n", name); } Left (enough space below)
72
String Input with gets The gets function Left (enough space below)
CSE123 Lec02 String Input with gets The gets function #define BUFLEN 200 int main() { char buf[BUFLEN]; gets(buf); printf("string: >%s<", buf); } allocate a large buffer (e.g., more than 2 lines) Array argument => array elements can be modified => input Schematic: Array will be modified 14-foreignNames.c #define BUFLEN 200 void main() { char name[BUFLEN]; printf("Name? "); gets(name); printf("Entered: %s\n", name); } Left (enough space below)
73
Notes gets deletes \n from input.
CSE123 Lec02 Notes gets deletes \n from input. If the user presses ENTER without any other characters, the first position will be the null character (called ‘empty string’). In case the user enters a string longer than the buffer, gets may cause a serious run-time error. Summarize; Questions Output simple; Input more complicated (stick to gets) Seen gets before? => getInt
74
String Output with puts
CSE123 Lec02 String Output with puts The puts function #define BUFLEN 200 int main() { char buf[BUFLEN]; gets(buf); puts(buf); return 0; } puts adds '\n' to output, equivalent to printf("%s\n", buf); Array argument => array elements can be modified => input Schematic: Array will be modified 14-foreignNames.c #define BUFLEN 200 void main() { char name[BUFLEN]; printf("Name? "); gets(name); printf("Entered: %s\n", name); } Left (enough space below)
75
Library String Functions
CSE123 Lec02 Library String Functions #include <string.h> Return the Length of a string size_t strlen(const char *str) Copy a string (including the '\0') src to dest char *strcpy(char *dest, const char *src) Concatenate two strings: append src to dest char *strcat(char *dest, const char *src) Compare two strings int strcmp(const char *s1, const char *s2) First: Must understand string operations => final In practice (homeworks), use library functions for convenience Return: 0 if identical; ASCII difference between the first mismatch otherwise >0 for, e.g., "abc" vs. "abb", <0 for "abc" vs. "abd"
76
strcpy example #include <string.h> char words[100];
strcpy(words, “Hello!”);
77
Structures To group multiple (heterogeneous) variables
CSE123 Lec02 Structures To group multiple (heterogeneous) variables Similar to Java classes, but not as powerful A structure has only data members All members are public Procedural vs. Data abstraction OO in C++ and Java
78
Structure Type Declaration
CSE123 Lec02 Structure Type Declaration Pattern struct StructType { /* members */ }; Typically global Members Analogous to data declaration struct Aircraft{ char id[10]; int x; int y; int z; int prevZ; int heading; int verticalSpeed; int speed; }; int main() { /* skipped */ } Schematic Why global?
79
Struct Instance Aircraft identifies a structure type, also known as a structure tag. a is an instance of the structure type Aircraft Keyword struct may not be dropped struct Aircraft { /*members*/ }; structure tag struct Aircraft a;
80
typedef A way to define a synonym for existing (complicated) types.
typedef int Bool; typedef int*** Intptr3;
81
typedef and Structures
CSE123 Lec02 typedef and Structures This is a case of programmer laziness! Instead of struct Aircraft boeing747; use typedef struct Aircraft Arcrft; then Arcrft boeing747; Arcrft is a new user-defined type.
82
Structure Variable Declaration
CSE123 Lec02 Structure Variable Declaration typedef struct Ac{ char id[10]; int x; int y; int z; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft; int main() { Aircraft a, b, c; /* skipped */ } Global declaration
83
Member Assignment/Reference
CSE123 Lec02 Member Assignment/Reference typedef struct { char id[10]; int x; int y; int z; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft; int main() { Aircraft a; a.z = 0; a.prevZ = a.z; /* skipped */ } Assignment pattern structVar.memberName = exp; Reference pattern structVar.memberName Schematic
84
Structure Initialization
CSE123 Lec02 Structure Initialization Like array initializations, this only works at the time of declaration. Afterwards you must assign/initialize each member one by one. typedef struct { char id[10]; int x; int y; int z; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft; int main() { Aircraft a = {"N3NK", 0, 0, 0, 0, 270, 0, 0}; /* skipped */ }
85
Structure Assignment Pattern Each member’s value will be copied
CSE123 Lec02 Structure Assignment typedef struct { char id[10]; int x; int y; int z; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft; int main() { Aircraft a = {"N3NK", 0, 0, 0, 0, 270, 0, 0}; Aircraft b; b = a; /* skipped */ } Pattern structVar1 = structVar2; Each member’s value will be copied
86
Additional Examples typedef struct { int ssn; ssn float debt;
CSE123 Lec02 Additional Examples typedef struct { int ssn; float debt; } Person; int type; int value; int address; char name[32]; } Variable; ssn debt type value address name
87
Complex Structures Various structure members
CSE123 Lec02 Complex Structures Various structure members Basic types: int, double, char, etc. Arrays Pointers Structures Arbitrary combination possible typedef struct { int x; int y; int z; } Position; char id[10]; Position pos; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft;
88
Array of Structures typedef struct { char id[10]; Position pos;
CSE123 Lec02 Array of Structures typedef struct { char id[10]; Position pos; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft; int main() { Aircraft aircrafts[2] = { { init list for elem 0 }, { init list for elem 1 } }; aircrafts[0].pos.x = 0; }
89
Structure with Array of Structures
CSE123 Lec02 Structure with Array of Structures typedef struct { char id[10]; Position pos; int prevZ; int heading; int verticalSpeed; int speed; } Aircraft; int numOfAircrafts; Aircraft aircrafts[100]; } Radar; int main() { Radar r; r.aircrafts[0].pos.x = 0; }
90
CSE123 Lec02 Structure Arguments void updateStatus(Aircraft b) { b.heading += 90; } int main() { Aircraft a = initialization; updateStatus(a); return 0; The argument variable b is a copy of the original variable a. Analogous to basic variables, different from arrays Cannot change the original variable a Schematic
91
Structure Return The local variable b is modified and returned.
CSE123 Lec02 Structure Return Aircraft updateStatus(Aircraft b) { b.heading += 90; return b; } int main() { Aircraft a = initialization; a = updateStatus(a); The local variable b is modified and returned. The returned b can be assigned (copied) to the original a. Schematic Potential disadvantages? Extra local allocation (esp. for large data) Copying process may slow down
92
CSE123 Lec02 Pointer to Structure To modify the original value, pass the pointer to a structure void updateStatus(Aircraft *b) { (*b).heading += 90; } int main() { Aircraft a = initialization; updateStatus(&a); return 0; Schematic Passing a pointer to showStatus? OK: to be consistent with structure argment passing NG: if don't want to allow to modify
93
CSE123 Lec02 Shorthand To deal with pointers to structure, the shorthand form is more commonly used. Pattern StructPtrVarmember-of-structure; void updateStatus(Aircraft *b) { b->heading += 90; /* same as (*b).heading */ } int main() { Aircraft a = initialization; updateStatus(&a); return 0;
94
Summary: pointers to structures
Aircraft a; Aircraft *a2 = &a; (*a2).heading = 90; Is equivalent to a2->heading = 90
95
File I/O Accessing a stream in C is done through file pointers:
A variable pointing to a file FILE *fp; The type FILE is defined in stdio.h Certain streams have predefined pointers with standard names – stdin, stdout and stderr fp
96
Opening/Closing a File
CSE123 Lec02 Opening/Closing a File fp = fopen("file.dat", "r") Full path name as well as the filename may be included btw the quotes Always test against NULL Closing a file when done: fclose(fp); "r" – reading "w" – writing (overwriting)! "a" – appending filename Returns the null pointer NULL (zero) on error, i.e. trying to read a file that doesn’t exist.
97
Reading Reading a char– returns char read or EOF int fgetc(FILE *fp)
CSE123 Lec02 Reading Reading a char– returns char read or EOF int fgetc(FILE *fp) int getc(FILE *fp) // macro int getchar() <==> int fgetc(stdin) Reading a string char *fgets(char *s, int size, FILE *fp) Reads in at most (size-1) characters and stores them in the buffer pointed by s Reading stops after a newline of EOF ‘\0’ is stored after the last character char *gets(char *s, int size) // from stdin fgets includes '\n'
98
Writing Writing a char– returns char written Writing a string
CSE123 Lec02 Writing Writing a char– returns char written int fputc(int c, FILE *fp) int putc(int c, FILE *fp) // macro int putchar(int c) <==> int fputc(…, stdin) int ungetc(int c, FILE *fp) //pushes c back to stream where it is //available for subsequent read operations Writing a string int fputs(const char *s, FILE *fp) Writes the string and a training newline into fp int puts(const char *s) // to stdout fgets includes '\n'
99
Example: File Copy by Line
CSE123 Lec02 Example: File Copy by Line int main() { char buf[BUFLEN], inFile[BUFLEN], outFile[BUFLEN]; FILE *in, *out; printf("Enter source filename: "); fgets(inFile,BUFLEN-1,stdin); trim_newline(inFile); // get outFile as well from user in = fopen(inFile, "r"); out = fopen(outFile, "w"); if ((in == NULL) || (out == NULL)) { printf("*** File open error\n"); return; } /* NULL returned at EOF */ while (fgets(buf, BUFLEN-1, in) != NULL) { fputs(buf, out); fclose(in); fclose(out); return 0; Schematic Exercises (possibly in small groups) Change case Cryptology (encoding/decoding) Summary Questions filecopy2.c
100
Formated I/O Reading – returns number of matches or EOF
CSE123 Lec02 Formated I/O Reading – returns number of matches or EOF int fscanf(FILE *fp, "...", variableList); Writing – returns number of chars written int fprintf(FILE *fp, "...", variableList); scanf is equivalent to fscanf with stdin printf to fprintf with stdout fgets includes '\n'
101
Buffering and fflush(…)
A buffer is an area of memory that acts as a temporary holding area for I/O Characters/strings are not usually written to a file as son as they are written to a stream They are accumulated in buffer and written to file as a block To force the buffer to be written to file, use: fflush(FILE *fp) Otherwise, buffer is flushed when full, or when stream is closed, or at exit.
102
Dynamic Memory Allocation
The most important usage of pointers. C’s data structures are normally fixed in size, i.e. static. Static data structures must have their sizes decided at time of compilation Arrays are good examples Through pointers, C supports the ability to allocate storage during program execution.
103
The Heap The pool of memory from which dynamic memory is allocated is separate, and is known as the heap. There are library routines to allocate and free memory from the heap. Heap memory is only accessible through pointers. Mixing statically and dynamically allocated memory is not allowed.
104
malloc() and free() Library routines for managing the heap
Dynamically allocate and free arbitrary-sized chunks of memory in any order void *malloc (size_t size); Allocates a block of size bytes from the heap Returns a pointer to the block allocated (casting to correct type required, value pointed by void * cannot be accessed directly.) size_t is an unsigned integer type used for very large integers. On failure, malloc returns a null pointer. Make sure to test for error void free (void *ptr); frees memory space pointed by ptr. #include<stdlib.h>
105
Example: Allocating an int Array
a = (int *) malloc(sizeof(int)*6); a[5] = 3; free(a); Never attempt to free memory that has not been previously allocated via malloc! Memory allocated through malloc is not cleared or initialized in anyway. Initialize yourself!
106
Example: String Allocations
CSE123 Lec02 Example: String Allocations char* newStr(char *str) { char *s; s = (char *) malloc(strlen(str) + 1); return strcpy(s, str); } char* newStr2(char *str, char *str2){ char *s; s = (char *) malloc(strlen(s) + strlen(s2) + 1); strcpy(s, str); return strcat(s, str2); } Schematic No details about malloc Sufficient to understand it as used in newString By default void* will be casted to char*, so in fact no casting is necessary here.
107
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
0xffffffff Text Data BSS Heap Stack char *p1 = malloc(3); char *p2 = malloc(4); char *p3 = malloc(1); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5);
108
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
0xffffffff Text Data BSS Heap Stack char *p1 = malloc(3); char *p2 = malloc(4); char *p3 = malloc(1); free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p1
109
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p2
110
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p2 p3
111
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p3 p2
112
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p1 0xffffffff Text Data BSS Heap Stack p2 p3 p4
113
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); p1 0xffffffff Text Data BSS Heap Stack p2 p3 p4
114
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p2,p5 p3 p4
115
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p2,p5 p3 p4
116
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p2,p5 p3 p4
117
Dynamic Memory Layout char *p1 = malloc(3); char *p2 = malloc(4);
free(p2); char *p4 = malloc(6); free(p3); char *p5 = malloc(2); free(p1); free(p4); free(p5); 0xffffffff Text Data BSS Heap Stack p1 p2,p5 p3 p4
118
The Love-hate Relationship with malloc
Most experience C-programmers have such a dilemma. malloc is fast, efficient and flexible The dreaded memory leak – neglecting to free memory Reaching beyond malloced bounds Heap fragmentation – this is not really a programming error, and is therefore even harder to fix
119
Summary Learn how to handle memory management in C
CSE123 Lec02 Summary Learn how to handle memory management in C malloc and related functions are essential to C programming Watch for the following common errors Not checking to see if malloc returned NULL No freeing memory after use: memory leak Dangling pointes: trying to access memory after freeing Set pointer to NULL after freeing it, otherwise it wil still hold the adress of the memory space that you freed Can we get away from pointers in C? Question?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.