Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this C code wrong?

Tags:

c

I know that pointers contain the addresses of variables, for example:

int c = 5;
int *p;  
p = &c;
printf("%d",*p); // Outputs 5.

But what if I want to send an address to a function:

void function (int *p)
{
  p++;
}
int c;
function (&c);

When function is called, the value of &c is assigned to int *p. I guess that the exact instruction is: *p = &c;, but I don't understand what this means.


1 Answers

I prefer to write int* p = &c;, that is, a pointer to type int is being assigned the address of c.

Pointer notation can be confusing, as you've noticed, because these two are equivalent:

int *p = &c;

and

int *p;
p = &c;

Hope this helps!

EDIT: The confusion comes because * is used both as the dereference operator, and for declaring a pointer. So when p contains the address of c, *p dereferences the pointer and returns the value of c. But when you say int *p = &c;, the * is saying "p is a pointer to an int", but is not doing any dereferencing.

like image 70
Skilldrick Avatar answered Aug 05 '26 18:08

Skilldrick



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!