You are on page 1of 12

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
i.e., it points to another variable

double cost = 100.00;

cost:1024 100.00

double *cost_ptr = &cost;

cost_ptr:2048 1024
Pointers
A pointer contains the address of another
memory cell
i.e., it points to another variable

double cost = 100.00; printf(cost: %lf, cost);

cost:1024 100.00 printf(cost_ptr: %d, cost_ptr);

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

double *cost_ptr = &cost; printf(&cost_ptr: %d, &cost_ptr);

cost_ptr:2048 1024 printf(*cost_ptr: %lf, *cost_ptr);


Pointers
A pointer contains the address of another
memory cell
i.e., it points to another variable

double cost = 100.00; cost: 100.00

cost:1024 100.00 cost_ptr: 1024

&cost: 1024

double *cost_ptr = &cost; &cost_ptr: 2048

cost_ptr:2048 1024 *cost_ptr: 100.00


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); Prints:
}
a=1, b=5
void swap(int a, int b) a=5, b=1
{
int tmp = a;
a = b;
b = tmp;
printf(a=%d, b=%d, a, b);

}
Call By Value

a:1036 5

b:1032 1

main

a:1028 5 a:1028 1

b:1024 1 b:1024 5
swap
Call By Reference

a:1036 5

b:1032 1

main

a:1028

b:1024
swap
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

a:1036 1

b:1032 5

main

a:1028 a:1028

b:1024 b:1024
swap
fraction.c
Create a single function that will multiply a
fraction.

You might also like