Reputation: 1989
Here, I've provided a simple code that uses a pointer.
void rets(int *px, int *py)
{
*px = 3;
*py = 5;
}
int main()
{
int x, y;
rets(&x, &y);
printf("First is %d, second is %d", x, y);
}
I just want it to be cleared... In the declaration: int *px, *py;
, sets aside two bytes in which to store the address of an integer variable and gives this storage space the name px. It also sets aside another two bytes in which to store the address of another integer variable and gives this space the name py. The asterisks tell the compiler that these variables will contain addresses and not values (if I'm not mistaken?), and the int tells it that the addresses will point to integer variables. But — and herein lies the source of much confusion:
*px = 3;
*py = 5;
it's used in a slightly different way here than it is in pointer declarations. What does it mean?
Upvotes: 3
Views: 6505
Reputation: 4578
basically, '*' is used in 3 different ways in C(unless I missed something), depending on the context
let's ignore #1.
when you have something like
TYPE * x;
this declares a variable x which holds a pointer to a value of type TYPE.
whereas when you have
*x
with x being a pointer, this refers to what x is pointing to, which is known as dereferencing(since pointers are also known as references)
Upvotes: 1
Reputation: 27248
*px = 3;
*py = 5;
It means that you give the value 3
to the memory pointed by the pointer px
and you give the value 5
to the memory pointed by the pointer py
.
Upvotes: 4
Reputation: 1077
So in the function declaration, you are declaring pointers to int that will be passed as parameters. In the definition you are dereferencing the pointers so actually using the variables space declared in main. If you didn't dereference, you would just be changing the pointer not what is pointed at. Where you call rets(), you are giving the address of the variables defined in main using &.
Upvotes: 4