Structure introduction

Structure in c language is a user defined datatype that allows you to hold different type of elements.
Difference between arrays and structures
An array is a collection of related data elements of same type. Structure can have elements of different types.
Syntax for defining structure :

//The struct keyword is used to define structure
struct structure_name
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeberN;
};


Important Points :
  • The closing brace '}' in the structure type declaration must be followed by a semicolon ';'.
  • Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined.
If you want to store data about a book. Like Data related to name(string), price(float), pages(integer).
Then the structure is defined as:
Example :

struct book
{
    char name[50];
    float price;
    int pages;
};


Explanation :
struct- is a keyword.
book- is the tag name of the structure
name, price, pages- are the members or fields of the structure

Declaring a structure variable :
Once the new structure data type has been defined one or more variables can be declared to be of that type.
For example the variables b1, b2, b3 can be declared to be of the type struct book.

Syntax :

struct book b1, b2, b3;

This statement will create space in the memory to hold all the elements in the structure, 
in this case it will be 7 bytes 
  • 1byte for char(name)
  • 4byte for float(price)
  • 2byte for integer(pages)

Examples for declaring structure :

struct book
{
    char name;
    float price;
    int pages;
};

struct book b1, b2, b3;

struct book
{
    char name;
    float price;
    int pages;
} b1, b2, b3;

struct
{
    char name;
    float price;
    int pages;
} b1, b2, b3;

Post a Comment

0 Comments