Add

Structures in C programming, need.


Structures in C, is 0.an advance and most popular topic in C language. It facilitates you to design your custom data type. In this tutorial, we will learn about structures in C its need, how to declare, define and access structures.

Need of structures in C?

 has built in primitive and derrived data types. Still not all real world problems can be solved using those types. You need custom data type for different situations.

For example, if you need to store 100 student record that consist of name, age and mobile number. To code that you will create 3 array variables each of size 100 i.e. name[100], age[100], mobile[100]. For three fields in student record it say seem feasible to you. But, think how cumbersome it would be to manage student record with more than 10 fields, in separate variables for single student.

What is structure in C?

Structure is a user defined data type. It is a collection of different data type, to create a new data type.

For example, You can define your custom type for storing student record containing name, age and mobile. Creating structure type will allow you to handle all properties (fields) of student with single variable, instead of handling it separately.

How to declare, define and access structure members?

To declare or define a structure, we use struct keyword. It is a reserved word in the C compiler. You must only use it for structure or its object declaration or definition.

Syntax to define a structure

struct structure_name

{

    member1_declaration;

    member2_declaration;

    ...

    ...

    memberN_declaration;

};

Here, structure_name is name of our custom type. memberN_declaration is structure member i.e. variable declaration that structure will have.

Example to define a structure

Let us use our student example and define a structure to store student object.

struct student

{

    char name[40];        // Student name

    int  age;             // Student age

    unsigned long mobile; // Student mobile number

};

Points to remember while structure definition

You must terminate structure definition with semicolon ;.

You cannot assign value to members inside the structure definition, it will cause compilation error. Since you are defining type you aren't associating data.

For example, following is an invalid structure definition.

struct student

{

    char name[40] = "sabi";

    int  age      = 21;

    unsigned long mobile = 123456789;

};

You can define a structure anywhere like global scope (accessible by all functions) or local scope (accessible by particular function).

Structure member definition may contain other structure type.

 

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.