I'm just starting out with pointers, and I'm slightly confused. I know &
means the address of a variable and that *
can be used in front of a pointer variable to get the value of the object that is pointed to by the pointer. But things work differently when you're working with arrays, strings or when you're calling functions with a pointer copy of a variable. It's difficult to see a pattern of logic inside all of this.
When should I use &
and *
?
The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable. It is known as value of operator.
Answer: * Operator is used as pointer to a variable. Example: * a where * is pointer to the variable a. & operator is used to get the address of the variable.
The fundamental rules of pointer operators are: The * operator turns a value of type pointer to T into a variable of type T . The & operator turns a variable of type T into a value of type pointer to T .
This & symbol is called an ampersand. This & is used in a unary operator. The purpose of this address operator or pointer is used to return the address of the variable.
You have pointers and values:
int* p; // variable p is pointer to integer type int i; // integer value
You turn a pointer into a value with *
:
int i2 = *p; // integer i2 is assigned with integer value that pointer p is pointing to
You turn a value into a pointer with &
:
int* p2 = &i; // pointer p2 will point to the address of integer i
Edit: In the case of arrays, they are treated very much like pointers. If you think of them as pointers, you'll be using *
to get at the values inside of them as explained above, but there is also another, more common way using the []
operator:
int a[2]; // array of integers int i = *a; // the value of the first element of a int i2 = a[0]; // another way to get the first element
To get the second element:
int a[2]; // array int i = *(a + 1); // the value of the second element int i2 = a[1]; // the value of the second element
So the []
indexing operator is a special form of the *
operator, and it works like this:
a[i] == *(a + i); // these two statements are the same thing
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