Pointers and Output Parameters
Pointers A pointer contains the address of another memory cell –i.e., it “points to” another variable cost:1024 cost_ptr:2048 double cost = ; double *cost_ptr = &cost;
Pointers A pointer contains the address of another memory cell –i.e., it “points to” another variable cost:1024 cost_ptr:2048 double cost = ; double *cost_ptr = &cost;
Pointers A pointer contains the address of another memory cell –i.e., it “points to” another variable cost:1024 cost_ptr:2048 double cost = ; 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);
Pointers A pointer contains the address of another memory cell –i.e., it “points to” another variable cost:1024 cost_ptr:2048 double cost = ; double *cost_ptr = &cost; cost: cost_ptr: 1024 &cost: 1024 &cost_ptr: 2048 *cost_ptr:
Call By Value int 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); }
Call By Value int 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=5 a=5, b=1
Call By Value 5 a: b:1032 main swap 5 a: b: a: b:1024
Call By Reference 5 a: b:1032 main swap a:1028 b:1024
Call By Reference int 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); }
Call By Reference 1 a: b:1032 main swap a:1028 b:1024 a:1028 b:1024
fraction.c Create a single function that will multiply a fraction.