pointers and output parameters
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 PresentationTRANSCRIPT
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;
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;
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);
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
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);
}
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
Call By Value
5a:1036
1b:1032
main
swap
5a:1028
1b:1024
1a:1028
5b:1024
Call By Reference
5a:1036
1b:1032
main
swap
a:1028
b:1024
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);
}
Call By Reference
1a:1036
5b:1032
main
swap
a:1028
b:1024
a:1028
b:1024
fraction.c
• Create a single function that will multiply a fraction.