Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

* symbol in C pointers

Tags:

c

syntax

pointers

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?

like image 725
Aaron Avatar asked Dec 08 '25 20:12

Aaron


2 Answers

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 &.

like image 118
ColWhi Avatar answered Dec 11 '25 09:12

ColWhi


*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.

like image 31
Igor Avatar answered Dec 11 '25 08:12

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!