Krisana CHINNASARN 310211 C Programming & 310222 Computer Programming January 4, 2004
Today
Review Pointers
1/12/04
C Programming
Review
Character Functions
Input & Output? Testing Characters? Mapping Characters? Whats required?
1/12/04
C Programming
Review
String Functions
Length? Manipulation? Comparison? Searching? Whats required?
1/12/04
C Programming
Pointers
Pointer
An address of an object in memory
Does not allocate space for an object
Allocate space or assign address of a non-pointer object
1/12/04
C Programming
Pointer Examples
char *c; (pointer to char, not assigned) int b = 5; int *bptr = &b; char str[8]; char *s = str; bptr
5 b s str[0] str[7]
6
1/12/04
C Programming
1/12/04
C Programming
1/12/04
C Programming
1/12/04
C Programming
1/12/04
C Programming
10
Array
E.g, print(%d, ptr[5]);
Prints the 6th element of the array
1/12/04
C Programming
11
Programming Exercise
Write a program that
Declares a constant string Hello Declares a char pointer to this string Prints the string using the pointer
1/12/04
C Programming
12
Pointer Arithmetic
Same as arithmetic on regular variables
Examples
char s[10], *p = s + 5; ++p; p--; p += 3;
Programming Exercise
Write a program that
Uses pointer arithmetic to determine if the strings abba and abcdba are palindromes
1/12/04
C Programming
14
Using Pointers
String Functions
Use pointers for returned memory addresses E.g., char *p = strstr(s1, s2);
s1 s2 Say hello to my little friend little p
1/12/04 C Programming 15
Using Pointers
Call by Reference
Change the value of function parameters
Eliminate return statement
void increment (int *); void increment (int *num) { (*num)++; } void main () { int num = 0; increment(&num); print(%d\n,num); }
C Programming
1/12/04
16
Programming Exercise
Write a program that
Declares two strings
s1 = Hello, s2 = World
Prints the values of these strings Calls a function swap that changes the value of these two strings in memory such that
s1 = World, s2 = Hello
1/12/04
C Programming
17
Next Time
Reading and writing from/to Files
1/12/04
C Programming
18