Originally Posted by
bluej322
I'm trying not to delve into this too much , but in what scenario would you want to use an "address", rather than a "house"?
Any time a function calls for an address, and not a house.
Bu seriously, that is not too far from the truth. One significant place is when you are using functions. As C uses a pass by value scheme, i.e., when you give arguments to a function the values are "copies", you will need to pass a pointer (the address) in to the function, should you want to manipulate the value.
For example, consider the classic case of a swap function:
Code:
void swap(int x, int y)
{
int tmp;
tmp = x; /* Wrong -- We are only working on copies of the original values */
x = y;
y = tmp;
}
int main(void)
{
int x = 5;
int y = 2;
printf("x = %d and y = %d\n", x, y);
swap(x, y);
printf("x = %d and y = %d\n", x, y);
return 0;
}
The above code won't work, because the swap function is just working on copies of the variables in main. In order for it to work correctly, you need to give it access to the variables in main. The way you do this is to pass it the address of the variables (a pointer):
Code:
#include <stdio.h>
void swap(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
int main(void)
{
int x = 5;
int y = 2;
printf("x = %d and y = %d\n", x, y);
swap(&x, &y);
printf("x = %d and y = %d\n", x, y);
return 0;
}