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?
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 &.
*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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With