In this guideline we will see the difference between the * and & operators in C programming.
* Operator in C
The * operator is one of the widely used operators in the C programming language that is used to retrieve the values of a pointer. We also name * operator as a dereference-operator. By Using this operator, you can easily access the stored data in the memory using help of the address pointers. If you use it in the program you must have to initialize a pointer which are pointing to the address so that’s one can easily retrieve the stored value in the address pointer.
& Operator in C
& operator on the other hand is used to return the address of the operand in the memory location. Due to the & operator you can easily get the address of the variable which is referred to in the memory location. To see the address of the variable of any kind of data type you will have to give the name of the variable with the sign of &-operator.
Examples
Below are some examples of C programs that use * operator, & operator and a combination of both.
Example 1: Program Uses (*) Operator
int main() {
int A= 5;
int *p = &A;
printf("The Value of A is %d\n", *p);
return 0;
}
The code initializes variable A with value 5 then it declares a pointer-type variable to have some address of memory and in the printf function, it shows the value of address A which is 5.
Output
Example 2: Program Uses (&) Operator
int main ()
{
int var1 = 1000;
int var2;
var2 = &var1;
printf (" The memory-location address of var2 is %i", var2);
return 0;
}
In the above code, first, there is an integer variable var1 that has the value of 1000. There is another variable var2 that takes the address of variable var1. The address is then printed using the %i format specifiers.
Output
Example 3: Program Uses both & and * Operators
int main() {
int aa = 5, bb;
int *pp;
pp = &aa;
bb = *pp;
printf("-----the-address of aa is 0x%x\n-----", &aa);
printf("-----Addres of-bb is 0x%x\n-----", &bb);
printf("-----The value-of pp is 0x%x\n-----", pp);
printf("---------Now the value of aa is %d\n-----", aa);
printf("-------valuee of *pp iss %d\n-----", *pp);
printf("-----The value of bb is: %d----", bb);
return 0;
}
In the above C code, two simple integer variables are initialized and one pointer type variable *pp. Then we assign the aa address to pp and again dereference its value by bb variable. At the end, we print all the values by using the printf function.
Output
Conclusion
Operators have a very significant role in the programming language. In this article, we have discussed two operators that work with only single operands and use to raise the performance of code in the C programming language. Both * and & operators infer in their meaning and functionalities as * is used for “returns the variable value” while & is for “manipulation of values on running time by taking memory addresses”.