as

Thursday, 13 November 2014

Nested Structure in C


 Nested structure in C is nothing but structure within structure. One structure can be declared inside other structure as we declare structure members inside a structure. The structure variables can be a normal structure variable or a pointer variable to access the data. You can learn below concepts in this section.
  •          Structure within structure in C using normal variable
  •          Structure within structure in C using pointer variable

Structure within structure  using normal variable
#include<stdio.h>


struct Department
{
    int dept_id;
    char dept_name[50];
};

struct Employee
{
    int id;
    char name[20];
    float sal;
    // structure within structure
    struct Department dept;
}emp;

void main()
{
    struct Employee emp = {12,"Sagar",15000,53,"Testing"};

printf("Department Id is:%d \n" ,emp.dept.dept_id);
printf("Department Name is:%s \n",emp.dept.dept_name);
 printf(" Id is: %d \n", emp.id);
 printf(" Name is: %s \n", emp.name);
 printf(" Salary is: %f \n\n", emp.sal);
    
 getchar();
}


Structure within structure  using pointer variable
#include<stdio.h>


struct Department
{
    int dept_id;
    char dept_name[50];
};

struct Employee
{
    int id;
    char name[20];
    float sal;
    // structure within structure
    struct Department dept;
}emp,*empptr;

void main()
{
    struct Employee emp = {12,"Sagar",15000,53,"Testing"};
    empptr=&emp;

  printf(" Department Id is: %d \n",empptr->dept.dept_id);
  printf(" Department Name is: %s \n",empptr->dept.dept_name);

  printf(" Id is: %d \n", empptr->id);
  printf(" Name is: %s \n",empptr-> name);
  printf(" Salary is: %f \n\n",empptr-> sal);

   
   getchar();
}







No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis