What's the Difference Between * and & in C?
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...
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?
7 Answers
Must Read
* and & as type modifiers
int ideclares an int.int* pdeclares a pointer to an int.int& r = ideclares a reference to an int, and initializes it to refer toi.
C++ only. Note that references must be assigned at initialization, thereforeint& 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)