Pointers in C | C programming

Pointers in C is a variable that stores the address of another variable. Others variables hold a value whereas, a pointer stores an address. It can be of type integer, char, array, etc.

Example:

int n = 10;    int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer. 

Usage of pointers

1) Dynamic memory allocation: In c language, using malloc() and calloc() functions we can dynamically allocate memory where the pointer is used.

2) Arrays, Functions, and Structures: Pointers in c language are widely used in arrays, functions, and structures. It helps reduce the code, improving the performance.

Declaring a pointer

In C, pointers are declared using the * (star/asterisk) symbol. It points to address of a variable.

Syntax:

int *x; //pointer to int   char *c; //pointer to char  

Pointer to array

int arr[20];   int *p[20]=&arr;  // Variable p of type pointer is pointing to the address of an integer array arr.  

Pointer to a function

void show (int);   void(*p)(int) = &display;  // Pointer p is pointing to the address of a function  

Pointer to structure

struct struct  {   int i;   float f;   } ref;   struct struct *p = &ref;  

c pointers
Example Program:

#include<stdio.h>  

int main () {   int number=50;     int *p;       p=&number; //stores the address of number variable     printf (“Address of p variable is %x \n”,p);  // p has the address of the number so p  . gives the address of number.     

printf (“Value of p variable is %d \n”,*p);  //*p- we get the value stored at the address given by p.    

return 0;   }    

Output:

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Representation of address

NULL Pointer

A pointer that is assigned NULL value is known as the NULL pointer. At the time of declaring the pointer, if there is no address to be specified in the pointer, we can assign a NULL value.

int *p=NULL;

The value of the pointer is 0 (zero) in most libraries.

Advantage of pointers

1) It reduces the code, improves the performance, is used to retrieving strings, trees, etc. and with arrays, structures, and functions.

2) Using pointers, we can return multiple values from functions.

3) You can access any memory location in the computer’s memory.

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!๐Ÿ‘‹
Can we help you?