Pointers In C

 

Pointers Definition :

Pointers in C language are is nothing but sort of like a variable which works like a locator/indicator to an address values (hence the name pointer).It helps in reducing the code and returning multiple values from a function.

 

Pointer in C

Syntax Of Pointers In C :

datatype * var_name;

The * operator creates a pointer variable, which points to a data type (like an int) of the same type.The pointer is given the address of the variable you are working with.

Pointers in C

Example :

In the below example, pointer is the address of the variable while *pointer and val print the value of the variable

Run
#include <stdio.h> 
int main()
{
	int val   = 40;  
	int* pointer;     // declaration of pointer

	pointer = &val;


	printf("1. Value at pointer = %p \n", pointer);
	printf("2. Value at val = %d \n", val);
	printf("3. Value at *pointer = %d \n", *pointer);
	return 0;
}

Output :

1. Value at pointer = 0x7fff0bf90d7c
2. Value at val = 40
3. Value at *pointer = 40

Uses of Pointers :

  • to pass references for arguments
  • In order to access array items
  • numerous values to be returned
  • Allocating memory dynamically
  • Data structures can be implemented easily.
  • Very easy to access memory address by Pointers.

Pointer Arithmetic :

Arithmetic of Pointers is different from integer. The following arithmetic of pointer are :

  • Increment/Decrement of Pointer.
  • Addition/ subtraction of integer to a Pointer.

Example :

In the below program, pointers are used to print the value of array elements.

Run
#include<stdio.h>

int main()
{
	int arr[4] = { 10, 20, 30, 40 };
	int* ptr;

	ptr = arr;
	printf("Elements of the array are: ");
	
	printf("%d, %d, %d, %d",ptr[0],ptr[1],ptr[2], ptr[3]);

	return 0;
}

Output :

Elements of the array are: 10, 20, 30, 40

Advantages of Pointers in C :

  • Arrays can be easily accessed by pointers.
  • Memory locations can be easily accessed by pointers.
  • Complex data structures can be easily built by the pointers.

Disadvantages of Pointers in C :

  • Pointers are hard to understand.
  • Pointers are slower than variable in C.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription