C pointer address operator



In the previous chapter we have learnt about more c programming basic pointer concept. In this chapter we will be learning about pointer address operator in C programming.

Pointer address operator in C Programming

  1. Pointer address operator is denoted by ‘&’ symbol
  2. When we use ampersand symbol as a prefix to a variable name ‘&’, it gives the address of that variable.

lets take an example –

&n  -  It gives an address on variable n

Working of address operator

#include<stdio.h>
void main()
{
int n = 10;
printf("\nValue of n is : %d",n);
printf("\nValue of &n is : %u",&n);
}

Output :

Value of  n is : 10
Value of &n is : 1002

Consider the above example, where we have used to print the address of the variable using ampersand operator.

In order to print the variable we simply use name of variable while to print the address of the variable we use ampersand along with %u

printf("\nValue of &n is : %u",&n);

Understanding address operator

Consider the following program –

#include<stdio.h>
int main()
{
int i = 5;
int *ptr;

ptr = &i;

printf("\nAddress of i    : %u",&i);
printf("\nValue of ptr is : %u",ptr);

return(0);
}

After declaration memory map will be like this –

int i = 5;
int *ptr;

C pointer address operator - step 1

after Assigning the address of variable to pointer , i.e after the execution of this statement –

ptr = &i;

C pointer address operator - step 2

Invalid Use of pointer address operator

Address of literals

In C programming using address operator over literal will throw an error. We cannot use address operator on the literal to get the address of the literal.

&75

Only variables have an address associated with them, constant entity does not have corresponding address. Similarly we cannot use address operator over character literal –

&('a')

Character ‘a’ is literal, so we cannot use address operator.

Address of expressions

(a+b) will evaluate addition of values present in variables and output of (a+b) is nothing but Literal, so we cannot use Address operator

&(a+b)

Conclusion

Thus we have learnt –

  1. About address operator
  2. How Address Operator is used to access the address of Variable
  3. Different illegal or wrong ways of using address operator
  4. Visual Understanding about Address operator

In the next chapter we will be learning Memory Organisation of Pointer Variable.