facebook like button

28 May, 2011

program 48: building and accessing structure in C

The need: 
      This is a program to demonstrate the use of structure in C program. This shows how a struct keyword can be used to define a structure form a collection of several variables of different (or may be same) type and how individual members of any struct type variable can be accessed and modified.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
struct student        //defining structure
{
  char name[20];
  int age,roll_no;
  char gender;
};

int main()
{
  struct student st;     //creation of new structure variable st which is like student in its structure
  strcpy(st.name,"RANU");
  st.roll_no=1;
  st.age=21;
  st.gender='m';
  printf("roll_no\tname\tage\tgender\n");
  printf("%d\t%s\t%d\t%c\n",st.roll_no,st.name,st.age,st.gender);
  return 0;
}

--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how we can access individual components of a structure so here I have not taken any input form user. All the values are directly assigned to structure component variables. We can scan individual components this will be shown in next post. There are 2 steps in using structures. First is defining the structure. In this step no memory is allocated (Like in our case no memory is allocated to student. This is only an abstraction of the structure.). Once the structure is defined we can use that structure in creating new variables which are like student (in our case st is the a structure variable created with the help of previously defined structure student. In this case memory has been allocated to variable st). Let me recall you, "Unless memory is allocated a variable can not be used to store anything."

Remarks:
1. Structures can be used to define a new data-type. This will be shown in upcoming posts.
2. One other thing like structure is union. union is the data-structure I hardly use unless its specified to use.




No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply