19_pdfsam_cs2022 - Or: dangerous and hard to use What does...

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

View Full Document Right Arrow Icon
Another example: swap This swap() function works as expected 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 “2 1” }
Background image of page 1

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

View Full DocumentRight Arrow Icon
scanf scanf uses this technique to modify its parameters int I; printf(“enter an integer: “); scanf(“%d”, &I); passes pointer to I to scanf
Background image of page 2
Another example void main() { int a = 3, b = 3; int *pa, *pb; pa = &a; pb = &b; if( pa == pb ) printf( "pa & pb equal.\n" ); if( *pa == *pb ) printf( "*pa & *pb equal.\n" ); (*pa)++; *pb += *pa; printf( "a: %d, b: %d\n", a, b ); pb = pa; *pa += *pb; printf( "a: %d, b: %d\n", a, b ); if( pa == pb ) printf( "pa & pb equal.\n" ); if( *pa == *pb ) printf( "*pa & *pb equal.\n" ); *((0 > 1) ? &a : &b) = 5; } ... 303 304 305 a b pa pb 306 307 3 3 303 304
Background image of page 3

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

View Full DocumentRight Arrow Icon
Pointers are powerful and flexible
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: Or: dangerous and hard to use What does this code do? What does this code do? void main() { char *x; *x = a; } void main() { char x=a, *p = &x; *p++; printf(%c\n, *p); } More dangers with pointers What does this code do? int *function_3() { int b; b = 3; return &b; } void main() { int *a; a = function_3(); printf( "a is equal to %d\n", *a ); } Arrays To declare an array, use , e.g.: Arrays in C are fixed size: their size cant be changed The number between the brackets must be a constant You can give initial values for array elements, e.g.: // create an array with 5 integer elements int A[5]; // create an array with 5 integer elements int A[5] = {3, 7, -1, 4, 6};...
View Full Document

Page1 / 6

19_pdfsam_cs2022 - Or: dangerous and hard to use What does...

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