Structure
structure is a user-defined data type
It is the collection of different data elements
struct keyword is used to define a structure
dot operator(.) is used for accessing members.
when a variable is associated with a structure, the compiler allocates the memory for each member.
The size of structure is greater than or equal to the sum of sizes of its members.
The size of structure is greater than or equal to the sum of sizes of its members.
Individual member can be accessed at a time.
Syntax:
struct[structure name]
{
Member definition;
Member definition;
..
Member definition
};
Example:
struct
Employee
{
char name[50]; //1byte
memory
int id; //2 byte
float salary; //4byte
} e1;
Note
7
bytes memory is allocated because the compiler allocates
the memory for each member.
#include
<stdio.h>
#include<conio.h>
struct Employee
{
char name[50];
int
id;
float salary;
} e1;
void main()
{
clrscr();
printf("Enter Employee information:\n");
printf("Enter NAME: ");
scanf("%s", e1.name);
printf("Enter ID: ");
scanf("%d", &e1.id);
printf("Enter SALARY: ");
scanf("%f", &e1.salary);
printf("Employee Information:\n");
printf("Name: %s\n",e1.name);
printf("Id: %d\n",e1.id);
printf("Salary: %f\n", e1.salary);
getch();
}
Output:
Enter Employee information:
Enter NAME: surya
Enter ID: 123
Enter SALARY: 35000
Employee Information:
Name: surya
Id: 123
Salary: 35000.000000
Union
union is a user-defined data type
It is the collection of different data elements
union keyword is used to
define a structure
dot operator(.) is used for accessing members.
when a variable is
associated with a union, the compiler allocates the memory by
considering the size of the largest memory. So size of union is
equal to the size of largest member
only
one member can be accessed at a time.
Syntax:
union[union name]
{
Member definition;
Member definition;
..
Member definition
};
Example:
union Employee
{
char name[50]; //1byte memory
int id; //2 byte
float salary; //4byte
} e1;
Note
4 bytes
memory is allocated because the compiler
allocates the memory by considering the size of the largest
memory
#include <stdio.h>
#include<conio.h>
union Employee
{
char name[50];
int id;
float salary;
} e1;
void main()
{
clrscr();
printf("Enter Employee information:\n");
printf("Enter NAME:
");
scanf("%s",
e1.name);
printf("Enter ID:
");
scanf("%d",
&e1.id);
printf("Enter
SALARY: ");
scanf("%f",
&e1.salary);
printf("Employee
Information:\n");
printf("Name:
%s\n",e1.name);
printf("Id:
%d\n",e1.id);
printf("Salary:
%f\n", e1.salary);
getch();
}
Output:
Enter Employee information:
Enter NAME: surya
Enter ID: 101
Enter SALARY: 12456
Employee Information:
Name:
Id: 1178771456
Salary: 12456.000000
Note
Only salary is displayed here because the compiler
allocates the memory by considering the size of the largest
memory(salary is the largest size )
No comments:
Post a Comment