Address Operator & in C
Last Updated :
16 Oct, 2023
The Address Operator in C is a special unary operator that returns the address of a variable. It is denoted as the Ampersand Symbol ( & ). This operator returns an integer value which is the address of its operand in the memory. We can use the address operator (&) with any kind of variables, array, strings, functions, and even pointers.
Syntax
The address operator is generally used as a prefix to its operand:
&operand
where operand can be a variable, array, function, pointer, etc.
Address Operator in C
Examples of Address Operators
Example 1:
Simple C example to demonstrate how to use the address operator in our program.
C
#include <stdio.h>
int main()
{
int x = 100;
printf ( "The address of x is %p" , &x);
return 0;
}
|
Output
The address of x is 0x7fffe8f5591c
Explanation
A variable x was defined and initialized with the value 100 in the program above. We retrieved the address of this variable x by using the address operator (&) as the prefix and printed it using printf() function.
Note: The %p format specifier to print the address in hexadecimal form.
Generally, the value returned by the address operator is stored in the pointer variable and then the pointer is dereferenced to get the value stored in that address.
Example 2:
Using a pointer to store the address returned by the address operator and then dereferencing it.
C
#include <stdio.h>
int main()
{
int x = 1;
int * ptrX;
ptrX = &x;
printf ( "Value of x: %d\n" , *ptrX);
return 0;
}
|
Example 3:
Some standard functions like scanf() also require the address of the variable. In these cases, we use the address operator.
C
#include <stdio.h>
int main()
{
int number;
printf ( "Enter any number: " );
scanf ( "%d" , &number);
printf ( "The entered number is: %d" , number);
return 0;
}
|
Output
Enter any number: 10
The entered number is: 10
Address Operator Incompitable Entities in C
There are some entities in C for which we cannot use the address operator i.e. we cannot get the address of those entities in C. Some of them are:
- Register Variables
- Bit Fields
- Literals
- Expressions
Applications of Address Operator (&):
The address operator (&) is widely used in C programs to get the addresses of different entities. Some of the major and most common applications are:
- Passing Pointers as Function Arguments
- Pointer Arithmetic
- Implementing Data Structures
Share your thoughts in the comments
Please Login to comment...