C array of pointer to structure

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Array of Pointer to Structure

Suppose we have declared structure then we can create array of pointer to the structure. Syntax of the structure is as follow –

Syntax :

struct stud
{
    int roll;
    char name[10];
}*ptr[20];

Explaination of Code :

  1. Suppose we have to maintain database of 10 students .
  2. Here 10 Structures are Placed in the Memory and there base addresses are stored in Pointers .
  3. E.g ptr[0],ptr[1] stores the address of First & second structure respectively.
  4. Using the Array of Pointer the time required to access structure reduces.
  5. This is used in Dynamic Memory Allocation

Diagram :

Live Example :

#include<stdio.h>

struct stud
    {
    int roll;
    char name[10];
    }*ptr[10];

int main()
{
int i;

printf("Enter the Student Details : ");
for(i=0;i<3;i++)
    {
    ptr[i] = (struct stud *) malloc(sizeof(struct stud));

    printf("
Enter the Roll Number : ");
    scanf("%d",&ptr[i]->roll);
    printf("
Enter the Name : ");
    scanf("%s",ptr[i]->name);
    }

printf("
Student Details are : ");

for(i=0;i<3;i++)
    {
    printf("
Roll Number : %d",ptr[i]->roll);
    printf("
Name : %s",ptr[i]->name);
    }

return(0);
}

Output :

Enter the Student Details :
Enter the Roll Number : 1
Enter the Name        : Pritesh
Enter the Roll Number : 2
Enter the Name : Suraj

Enter the Roll Number : 3
Enter the Name : Aruna

Student Details are :
Roll Number : 1
Name : Pritesh
Roll Number : 2
Name : Suraj
Roll Number : 3
Name : Aruna