Docsity

Pointers in C: Passing Pointers to Functions, Study notes of Software Engineering

Partial preview of the text

Download Pointers in C: Passing Pointers to Functions and more Study notes Software Engineering in PDF only on Docsity!

POINTERS IN C,PASSING POINTERS TOFUNCTIONS CSSE 120—Rose Hulman Institute of Technology

Can functions modifyactual parameters? ^ In Python, no! (pass by value) ^ Consider this function:^ void

downAndUp(

int

takeMeHigher,

int

putMeDown){

takeMeHigher

+=

1;

putMeDown

-=

1;

}

^ How is this C function invoked?^ 

downAndUp(up, down);

^ Will calling the function change the values of theactual parameters

up

and

down

^ How do we modify downAndUp() so that it actuallychanges the values of its parameters?^ 

By passing pointers to the parameters to be changed

^ Together, implement a function that passes pointersto values to be changed^ 

Checkout project

PointersInclass

from SVN

^ Implement

downAndUpthatWorks()

^ Use function

testdownAndUpthatWorks()

to test

downAndUpthatWorks()

Pass pointers to values to bechanged

Pointer Assignments^ int

x=3,

y^

=^ 5;

int

*px

=^

&x;

int

*py

=^

&y;

printf(

"%d

%d\n"

,^ x,

y);

*px

=^

printf(

"%d

%d\n"

,^ x,

y);

x^

is^

changed

px^

=^ py; printf(

"%d

%d\n"

,^ x,

y);

x^

not

changed

*px

=^

printf(

"%d

%d\n"

,^ x,

y);

y^

is^

changed

Pointer Pitfalls ^ Don't try to dereference an unassigned pointer:^ 

int

*p; *p^

=^ 5;

/*^

oops!

Program

probably

dies!

*/

^ Pointer variables must be assigned

address

values.

^ int

x^

=^ 3; int

*p; p^ =

x^

/*^

oops,

RHS

should

be

&x

*/

^ Be careful how you increment^ 

*p +=1;

/*^

is^

not

the

same

as

…^

*/

^ *p++;

In-class exercise on pointer pitfalls ^ The rest of today’s quiz lets you see some pointerpitfalls in action. These make great exam questions! ^ Do it now ^ When you are done, start the homework:^ 

More pointer output  Writing functions to change variables^ ^ doubleMe^ ^ swap  scanf revisited