Docsity

CGS 3460 Lecture 29: Pointers, Address and Indirection Operators, and Arrays, Quizzes of Computer Science

Partial preview of the text

Download CGS 3460 Lecture 29: Pointers, Address and Indirection Operators, and Arrays and more Quizzes Computer Science in PDF only on Docsity!

Pointer (II)CGS 3460, Lecture 29Mar 24, 2006Hen-I Yang

Previously… „

What is a pointer?

Declare the type of pointers.

Agenda „

Address and Indirection Operators.

Use of Pointers.

Array and Pointers

int a;int b[3];char c;int * p1;char * p2;p1 = &a;p2 = &c;

a b

b c

p

p

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

Why do we use pointers? „

Pass as argument or Return the value

Dynamic variables

More efficient

Refer to part of the a larger variable

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 pointervariable when return type is a pointer

Arrays and Pointers „

Closely related in C (not so in otherlanguage)

Pointer is more efficient to use (array hascatch up with new compilers)

Insight into C

Critical in mastering C

How do these pointers work? „

*p++,

*(p++)

(*p)++

*++p,

*(++p)

++*p,

++(*p)

Array and Pointer (III)^ int a[10] = {0,1,0,1,0,1,0,1};int *p;int sum;for (p = &a[0]; p < &a[9]; p++) {

*sum += p;

for (p = a; p < a + 9; p++) {

*sum += p;

Equivalent

Summary „

Address and Indirection Operators.

Use of Pointers.

Arrays and Pointers

Before you go „

Read Chapter 12.

Exercise: 12.1, 12.

Homework 4 will take a much longer timethan previous ones.