Pointers in C

Pointers in C



What is Pointer ?

A pointer is a special variable whose value is the address of another variable. In simple word, Pointer is also kind of a variable that is used to store address of variables or a memory location.

How to initialize a Pointer ?

Defining Pointer is a step-by-step procedure, like this ->

Step 1: Defining a Pointer Variable
We need to define a Pointer variable first by specifying the data type and variable name.
Syntax : 

data_type *pointer_var;
  
Example : 

int *p;

//Here int is the data type of the pointer variable and ‘p’ is the name of that variable.
//The ‘*’ (asterisk) sign is used to declare the pointer.

Step 2: Assigning the Value
After declaring we need to assign the address of a variable to the pointer variable.
Syntax : 

pointer_var = &main_var;

Example : 
p = &var;

//Here ‘p’ is the pointer variable and ‘var’ is the name of that variable whose address is being stored.
//The ‘&’ (asterisk) sign is used to assign the address to a pointer.


A sample program of usage of Pointer Variable :


#include<stdio.h>

int main() {

	int Eruditors = 47;
	int *p;
	p = &Eruditors;
	//Instead of declaring & assigning separately we can declare & assign a pointer only once. For example,
	//int *p = &Eruditors;

	printf("Value of Eruditors Variable : %d\n",Eruditors);
	//Value assigned in int Eruditors variable

	printf("Value of *p Variable : %d\n",*p);
	//Value of *p variable that indicates to the value of Eruditors variable

	printf("Address stored in p Variable : %p\n",p);
	// Accessing the address using pointer variable

	printf("Address of Eruditors Variable : %p\n",&Eruditors);
	//Accessing the address without using pointer variable
	
	return 0;
}

Output :



Key Points about Pointer : 

  • ~ At the time of initializing, we can assign the 'NULL' value in a pointer variable. It assigns '0'. For example, int *p = NULL;
  • '%p' format specifier is used for pointer variable.
  • ~ Four arithmetic operators that can be used in pointers: ++, --, +, -
  • ~ C allows us to have pointer on a pointer and so on.

Advantages of an Pointer in C : 

  • ~ It reduces the code and improves the performance.
  • ~ We can get access of any memory location access by pointer.
  • ~ A pointer can be used to Arrays and Functions also.
  • ~ We can return multiple values from a function using the pointer.