pointers and output parameters

12
Pointers and Output Parameters

Upload: macey-saunders

Post on 30-Dec-2015

14 views

Category:

Documents


1 download

DESCRIPTION

Pointers and Output Parameters. Pointers. A pointer contains the address of another memory cell i.e., it “points to” another variable. double cost = 100.00;. cost:1024. 100.00. double *cost_ptr = &cost;. cost_ptr:2048. Pointers. A pointer contains the address of another memory cell - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Pointers and Output Parameters

Pointers and Output Parameters

Page 2: Pointers and Output Parameters

Pointers

• A pointer contains the address of another memory cell – i.e., it “points to” another variable

100.00cost:1024

cost_ptr:2048

double cost = 100.00;

double *cost_ptr = &cost;

Page 3: Pointers and Output Parameters

Pointers

• A pointer contains the address of another memory cell – i.e., it “points to” another variable

100.00

1024

cost:1024

cost_ptr:2048

double cost = 100.00;

double *cost_ptr = &cost;

Page 4: Pointers and Output Parameters

Pointers

• A pointer contains the address of another memory cell – i.e., it “points to” another variable

100.00

1024

cost:1024

cost_ptr:2048

double cost = 100.00;

double *cost_ptr = &cost;

printf(“cost: %lf”, cost);

printf(“cost_ptr: %d”, cost_ptr);

printf(“&cost: %d”, &cost);

printf(“&cost_ptr: %d”, &cost_ptr);

printf(“*cost_ptr: %lf”, *cost_ptr);

Page 5: Pointers and Output Parameters

Pointers

• A pointer contains the address of another memory cell – i.e., it “points to” another variable

100.00

1024

cost:1024

cost_ptr:2048

double cost = 100.00;

double *cost_ptr = &cost;

cost: 100.00

cost_ptr: 1024

&cost: 1024

&cost_ptr: 2048

*cost_ptr: 100.00

Page 6: Pointers and Output Parameters

Call By Valueint main(void){

int a = 5, b = 1;swap(a, b);printf(“a=%d, b=%d”, a, b);return (0);

}

void swap(int a, int b){

int tmp = a;a = b;b = tmp;printf(“a=%d, b=%d”, a, b);

}

Page 7: Pointers and Output Parameters

Call By Valueint main(void){

int a = 5, b = 1;swap(a, b);printf(“a=%d, b=%d”, a, b); return (0);

}

void swap(int a, int b){

int tmp = a;a = b;b = tmp;printf(“a=%d, b=%d”, a, b);

}

Prints:

a=1, b=5a=5, b=1

Page 8: Pointers and Output Parameters

Call By Value

5a:1036

1b:1032

main

swap

5a:1028

1b:1024

1a:1028

5b:1024

Page 9: Pointers and Output Parameters

Call By Reference

5a:1036

1b:1032

main

swap

a:1028

b:1024

Page 10: Pointers and Output Parameters

Call By Referenceint main(void){

int a = 5, b = 1;swap(&a, &b);printf(“a=%d, b=%d”, a, b); return (0);

}

void swap(int *a, int *b){

int tmp = *a; //follow the pointer to a, get the value, and store it in tmp*a = *b; *b = tmp;printf(“a=%d, b=%d”, *a, *b);

}

Page 11: Pointers and Output Parameters

Call By Reference

1a:1036

5b:1032

main

swap

a:1028

b:1024

a:1028

b:1024

Page 12: Pointers and Output Parameters

fraction.c

• Create a single function that will multiply a fraction.