Structure in C

A structure is a user defined data types, it is used to group a different type into a single type. It allocates contiguous memory locations, we can access the structure elements through structure variable along with dot operator or arrow operator depends upon the structure variable, if structure variable is pointer will use arrow operator else will use dot operator, memory will be arranged by structure padding. 

Declaration:  struct structure name

                        {         

                                    Structure members;

                                    ……

                                    ……

                        }s;

ex:

            struct dbase

            {

                        char a;

                        short b;

                        int c;

                        float d;                       

            }s;

Structure Initialization:

if we initialize a structure, need to create structure variable along with that will give value also

            Examples :

            struct dbase

            {

                        char ch;

                        short n1;

                        int n2;

                        float pi;

            }s = {‘z’, 12, 512, 3.14};

            In above example, struct is a keyword, dbase is a structure name/tag name it allocates 12 bytes contiguous manner. We can access the structure members along with structure variable with dot operator(ex. s.ch,s.n1,..)      

Structure Declaration:

1.If we declare a structure outside the main, it allocates space in data segment, if it inside the main it allocates in stack memory.

Examples:

            struct dbase

            {

                        char ch;

                        short n1;

                        int n2;

                        float pi;

            }s ;

int main()

{          s.ch = ‘z’;

            s.n1 = 12;

            s.n2 = 34;

            s.pi = 3.14;

            printf(“%c %hd %d %f\n”,s.ch,s.n1,s.n2,s.pi);

}

What is a structure pointer?

Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator.

#include<stdio.h>

struct dbase

{

            int x,y;

};

int main() {

            struct dbase p1 ={1,2};

            struct dbase *p2 = &p1;

            printf(“%d %d”,p1->x,p2->x);

}

Enquire Now

Enquire Now

Enquire Now

Please Sign Up to Download

Please Sign Up to Download

Enquire Now

Please Sign Up to Download

Enquiry Form

Quick Enquiry