What's the difference between * and & in C?

Cristian Ceron picture Cristian Ceron · Feb 28, 2015 · Viewed 43.9k times · Source

I'm learning C and I'm still not sure if I understood the difference between & and * yet.

Allow me to try to explain it:

int a; // Declares a variable
int *b; // Declares a pointer
int &c; // Not possible

a = 10;
b = &a; // b gets the address of a
*b = 20; // a now has the value 20

I got these, but then it becomes confusing.

void funct(int a) // A declaration of a function, a is declared
void funct(int *a) // a is declared as a pointer
void funct(int &a) // a now receives only pointers (address)

funct(a) // Creates a copy of a
funct(*a) // Uses a pointer, can create a pointer of a pointer in some cases
funct(&a) // Sends an address of a pointer

So, both funct(*a) and funct(&a) are correct, right? What's the difference?

Answer

emlai picture emlai · Feb 28, 2015

* and & as type modifiers

  • int i declares an int.
  • int* p declares a pointer to an int.
  • int& r = i declares a reference to an int, and initializes it to refer to i.
    C++ only. Note that references must be assigned at initialization, therefore int& r; is not possible.

Similarly:

  • void foo(int i) declares a function taking an int (by value, i.e. as a copy).
  • void foo(int* p) declares a function taking a pointer to an int.
  • void foo(int& r) declares a function taking an int by reference. (C++ only)

* and & as operators

  • foo(i) calls foo(int). The parameter is passed as a copy.
  • foo(*p) dereferences the int pointer p and calls foo(int) with the int pointed to by p.
  • foo(&i) takes the address of the int i and calls foo(int*) with that address.

(tl;dr) So in conclusion, depending on the context: