Computer >> Computer tutorials >  >> Programming >> C programming

Explain reference and pointer in C programming?


Problem

Explain the concept of reference and pointer in a c programming language using examples.

Reference

  • It is the alternate name for the variable that we declared.

  • It can be accessed by using pass by value.

  • It cannot hold the null values.

Syntax

datatype *variablename

For example, int *a; //a contains the address of int type variable.

Pointer

  • It stores the address of variable.

  • We can hold the null values using pointer.

  • It can be access by using pass by reference.

  • No need of initialization while declaring the variable.

Syntax

pointer variable= & another variable;

Example

#include<stdio.h>
int main(){
   int a=2,b=4;
   int *p;
   printf("add of a=%d\n",&a);
   printf("add of b=%d\n",&b);
   p=&a; // p points to variable a
   printf("a value is =%d\n",a); // prints a value
   printf("*p value is =%d\n",*p); //prints a value
   printf("p value is =%d\n",p); //prints the address of a
   p=&b; //p points to variable b
   printf("b value is =%d\n",b); // prints b value
   printf("*p value is =%d\n",*p); //prints b value
   printf("p value is =%d\n",p); //prints add of b
}

Output

add of a=-748899512
add of b=-748899508
a value is =2
*p value is =2
p value is =-748899512
b value is =4
*p value is =4
p value is =-748899508