19_pdfsam_cs2022

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

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

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” }

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

View Full Document
scanf scanf uses this technique to modify its parameters int I; printf(“enter an integer: “); scanf(“%d”, &I); passes pointer to I to scanf
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

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

View Full Document
Pointers are powerful and flexible

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

View Full Document
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 can’t 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

{[ snackBarMessage ]}

### 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
Ask a homework question - tutors are online