Structure in C Language

 INTRODUCTION

struct in the C programming language (and many derivatives) is a record declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the same address.

  • It is a collection / set of different data types. Like int, float, char etc. 
  • Each variable in structure is known as a member of the structure.
  • struct key word is used to define the structure.
  • Structure and union both are user define function.
  • Structure allocate separate memory, Union store all in one memory. 

Difference Between Structure And Union :

                                 STRUCTURE

                                       UNION

Use struct key word to define a structure.

Use union key word to define a union.

Every member within structure is assigned a unique memory location.

A memory location is shared by all the data members.

Changing the value of one data member will not affect other data member in structure.

Changing the value of one data member will affect other data member in structure.

The total size of the structure is the sum of the size of every data member.

Total size of the union is the size of the largest data member.

 - Both are user defined data type.

 -Both are using . operator for excessing the member.

Example :

-Example of STRUCTURE :

Code :

#include<stdio.h>

struct student

{

char *name;

int id;

int age;

};                                                                        //;  semicolon is important

int main()

{

struct student s1;

        s1.name="REVATI";                              //we can write . OR ->(arrow)

s1.id=1234;

s1.age=20;

printf("name :%s \n",s1.name);

printf("id :%d \n",s1.id);

printf("age :%d \n",s1.age);

}

output :

name :REVATI

id :1234

age :20


-Example of STRUCTURE  in STRUCTURE :

code :

#include<stdio.h>
//inner structure
struct address
{
char*city;
char*state;
char*country;
};
//outer structure
struct student_name
{
char*name;
int id;
int age;
struct address add;                                     //add=for inner structure
};
int main()
{
struct student_name s1;                               //s1=for outer structure
s1.name="REVATI";
s1.id=56789;
s1.age=20;
s1.add.city="MUMBAI";
s1.add.state="MAHARASHTRA";
s1.add.country="INDIA";
printf("name :%s \n",s1.name);
printf("id :%d \n",s1.id);
printf("age :%d \n",s1.age);
printf("city :%s \n",s1.add.city);
printf("state :%s \n",s1.add.state);
printf("countryu :%s \n",s1.add.country);
}

output :
name :REVATI
id :56789
age :20
city :MUMBAI
state :MAHARASHTRA
countryu :INDIA











No comments:

Post a Comment