13_pdfsam_cs2022 - cp = &x; *cp = z; cp =...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Pointers: a first example int main( void ) { int x = 3, z; // create a pointer variable, and // set it to the address of x int *ptr = &x; // set z to the value pointed to // by ptr z = *ptr; // Changes value at ptr *ptr = 4; } ... 303 304 305 3 3 303 x z ptr
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Don’t get confused! Pointer notation is confusing, especially at first *’s are used in two ways: in declarations, and as an operator In declarations, * creates a pointer variable, e.g. int *ptr; declares a pointer to variables of type int As an operator, * dereferences a pointer, e.g. *ptr returns the value stored in memory at the address contained in ptr
Background image of page 2
Another example ... 303 304 305 x y cp ip c 306 307 int main(void) { int x = 1, y = 2; int *ip; char c; char *cp; ip = &x; printf( "%d\n", *ip ); printf( "%d\n", *ip + 2 ); y = *ip; *ip = 0; printf( "%d\n", x );
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: cp = &x; *cp = z; cp = &c; *cp = z; printf( "%c\n", c ); return 0; } Passing pointers to functions Recall that foo changes local variable x, but not the original variable y void foo(int x) { x = 5; } int main(void) { int y = 10; foo(y); printf(%d\n, y); // prints 10, not 5 return 0; } Passing pointers to functions This version does modify y void foo(int * x) { * x = 5; } int main(void) { int y = 10; foo( & y); printf(%d\n, y); // prints 10, not 5 return 0; } Another example: swap This swap() function has no effect: void swap ( int a, int b ) { int temp = a; a = b; b = temp; } void main() { int A = 1, B = 2; swap(A, B); printf( "%d %d\n, A, B ); // prints 1 2 }...
View Full Document

This note was uploaded on 01/10/2010 for the course CS 2022 at Cornell University (Engineering School).

Page1 / 6

13_pdfsam_cs2022 - cp = &x; *cp = z; cp =...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online