130 likes | 290 Views
Pointer (I). CGS 3460, Lecture 28 Mar 22, 2006 Hen-I Yang. Previously…. Debug. Average: 63.3 Max: 92, Min: 16 81.3% get 90% or more. Grading Scale: Hw_Quiz 3 >70: 100% of the grade for homework 50 -- 69: 90% of the grade for homework 40 -- 49: 80% of the grade for homework
E N D
Pointer (I) CGS 3460, Lecture 28 Mar 22, 2006 Hen-I Yang
Previously… • Debug
Average: 63.3 Max: 92, Min: 16 81.3% get 90% or more Grading Scale: Hw_Quiz 3 >70: 100% of the grade for homework 50 -- 69: 90% of the grade for homework 40 -- 49: 80% of the grade for homework 30 -- 39: 60% of the grade for the homework 39 or below: at most 60% of the grade for the homework Result of Quiz 3
Agenda • What is a pointer? • Declare the type of pointers. • Address and Indirection Operators. • Use of Pointers.
What is a pointer? • Most important, most abstract, most misunderstood concept in C language. • Memory address and bytes. • Code and Data segments John Tim Jane Robert Ben Mary Lisa 101 102 103 104 105 106 107
p1 p2 101 102 103 105 106 107 int a; int b[3]; char c; int * p1; char * p2; p1 = &a; p2 = &c; a b c b
Why do we use pointers? • Pass as argument or Return the value • Dynamic variables • More efficient • Refer to part of the a larger variable
p1 p1 p2 Declare the Type of a Pointer • We can declare the type of pointer as any of the types we have introduced so far. • Which means int, float or char int a; int b[3]; char c; int * p1; char * p2; p1 = &b[0]; p2 = &c; p1++; p1++; a b c b
Address and Indirection Operator • Address operator: & • Indirection operator: * • &: Where does Robert lives? (&Robert = 104) • *: Who lives in room 101? John Tim Jane Robert Ben Mary Lisa 101 102 103 104 105 106 107
Use of Pointers: as argument • Pointer as argument • So the function can modify the value of the argument passed • C functions are “Pass by Value” • scanf(“%d”, &i); • Const modifier
Use of Pointers: as return value • Use pointer as return value int *max (int *a, int *b) { if (*a > *b) return a; else return b; } int *p, x, y; p = max (&x, &y); • Do not return local variable or local pointer variable
Summary • What is a pointer? • Declare the type of pointers. • Address and Indirection Operators. • Use of Pointers.
Before you go • Read Chapter 11. • Exercise: 11.1, 11.2, 11.4 • Start working on Homework 4. It will take a much longer time than previous ones. • Use the sample code (exec_seq3.c) given in last lecture to figure out problem 2 in quiz 3