0% found this document useful (0 votes)
46 views

Structure Union Enum Typedef

A structure is a user-defined data type that contains a collection of heterogeneous data elements grouped together under a single name. A structure allows different data types to be accessed sequentially through a single structure variable. The document then provides examples of how to declare a structure type, define structure variables, initialize structure members, access structure members using dot and arrow operators, pass structures to functions, create arrays of structures, and nest one structure within another.

Uploaded by

satya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Structure Union Enum Typedef

A structure is a user-defined data type that contains a collection of heterogeneous data elements grouped together under a single name. A structure allows different data types to be accessed sequentially through a single structure variable. The document then provides examples of how to declare a structure type, define structure variables, initialize structure members, access structure members using dot and arrow operators, pass structures to functions, create arrays of structures, and nest one structure within another.

Uploaded by

satya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Structure and union

A structure can be defined as a collection of different heterogeneous type of


elements. A structure contains a number of data types grouped together. These
data types may or may not be of the same type.
It is a derived datatype.

Declaring a Structure
Before declararion structure, first we have to design the structure.
Syntax:
struct Structurename
{
Member1;
Member 2;
Member 3;
};
Here structurename represents the name of structure given by the user and member
represent the information that we want to store in this structure.

struct Student
{
char name[20];
int rollno;
float marks;
}

Declararion of structure variable:

struct structname
{
Member1;
Member 2;
Member 3;
}
struct structname Structurevariablename;
struct Student
{
char name[20];
int rollno;
float marks;
};

struct Student s1;


Memory representation structure:
Memory will be allocated to the structure variable, not to the member. Sizeof structure
will be equal to the sum of the sizeof each member of the structure.
struct Student
{
char name[50];
int rollno;
float marks;
};
struct Student s1;
Total memory occupied by structure s1 variable: 58 bytes
50bytes(char) + 4 bytes(int)+4 bytes(float)

Note the following points while declaring a structure type:


• The closing brace ( } ) in the structure type declaration must be followed by a
semicolon ( ; ).
• It is important to understand that a structure type declaration doesnot tell the
compiler to reserve any space in memory. All a structuredeclaration does is, it
defines the ‘form’ of the structure.
• Usually structure type declaration appears at the top of the source code file,
before any variables or functions are defined. In very large programs they are
usually put in a separate header file, and the fileis included (using the
preprocessor directive #include) in whichever program we want to use this
structure type.
• If a structure variable is initiated to a value { 0 }, then all its elements are set to
value 0,

//initialization of structure
struct Student
{
char name[50];
int rollno;
float marks;
};
struct Student s1= { "Manas",13, 54.5 } ;
struct Student s2= { "Karan",18, 90 } ;
struct Student s3= { 0 } ;

//runtime initialization:
It will run with the help of scanf().

How to access member of structure


Member of a structure can be accessed using dot operator or member operator or
period operator.
struct student s1;
structure variable.membername;
s1.name;
s1.rollno;
s1.marks;
Structure elements can be accessed through a pointer to a structure using the arrow (->)
operator.
struct student *s1;
s1->name;
s1->rollno;
s1->marks

* Memory map of structure elements */


# include <stdio.h>
int main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "Address of name = %u\n", &b1.name ) ;
printf ( "Address of price = %u\n", &b1.price ) ;
printf ( "Address of pages = %u\n", &b1.pages ) ;
return 0 ;
}
Output:
Address of name = 65518
Address of price = 65519
Address of pages = 65523
Additional Features of Structures
• All elements of one structure variable can be assigned to another structure
variable of the same type using the assignment (=) operator.
//copy the elements of structure
# include <stdio.h>
# include <string.h>
int main( )
{
struct employee
{
char name[ 10 ] ;
int age ;
float salary ;
};
struct employee e1 = { "Sanjay", 30, 5500.50 } ;
struct employee e2, e3 ;
/* piece-meal copying */
strcpy ( e2.name, e1.name ) ;
/* e2.name = e1. name is wrong */
e2.age = e1.age ;
e2.salary = e1.salary ;
/* copying all elements at one go */
e3 = e2 ;
printf ( "%s %d %f\n", e1.name, e1.age, e1.salary ) ;
printf ( "%s %d %f\n", e2.name, e2.age, e2.salary ) ;
printf ( "%s %d %f\n", e3.name, e3.age, e3.salary ) ;
return 0 ;
}
Output:

Sanjay 30 5500.500000
Sanjay 30 5500.500000
Sanjay 30 5500.500000

Nested structure:
When the member of a structure is a structure itself, then it is called nested structure.

One structure can be nested within another structure.


# include <stdio.h>
int main( )
{
struct address
{
char area[ 15 ] ;
char city[ 25 ] ;
int pin ;
};
struct emp
{
char name[ 25 ] ;
struct address a ;
};
struct emp e = { "jeru", "531046", "nagpur", 10 };
printf ( "name = %s phone = %s\n", e.name, e.a.phone ) ;
printf ( "city = %s pin = %d\n", e.a.city, e.a.pin ) ;
return 0 ;
}
Output:
name = jeru phone = 531046
city = nagpur pin = 10
It is possible to pass a structure variable to a function either by value or by address.
/* Passing individual structure elements */
# include <stdio.h>
void display ( char *, char *, int ) ;
int main( )
{
struct book
{
char name[ 25 ] ;
char author[ 25 ] ;
int callno ;
};
struct book b1 = { "Let us C", "YPK", 101 } ;
display ( b1.name, b1.author, b1.callno ) ;
return 0 ;
}
void display ( char *s, char *t, int n )
{printf ( "%s %s %d\n", s, t, n ) ;

output...
Let us C YPK 101
//Structure Pointer
How to access elements when structure variable is a pointer
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly we
can have a pointer pointing to a struct. Such pointers are known as ‘structure pointers’.
# include <stdio.h>
int main( )
{
struct book
{
char name[ 25 ] ;
char author[ 25 ] ;
int callno ;
};
struct book b1 = { "Let us C", "YPK", 101 } ;
struct book *ptr ;
ptr = &b1 ;
printf ( "%s %s %d\n", b1.name, b1.author, b1.callno ) ;
printf ( "%s %s %d\n", ptr->name, ptr->author, ptr->callno ) ;
return 0 ;
}

//It is possible to create an array of structures.


/* Usage of an array of structures */
# include <stdio.h>
void linkfloat( ) ;
int main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b[ 100 ] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "Enter name, price and pages " ) ;
fflush ( stdin ) ;
scanf ( "%c %f %d", &b[ i ].name, &b[ i ].price, &b[ i ].pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "%c %f %d\n", b[ i ].name, b[ i ].price, b[ i ].pages ) ;
return 0 ;
}
void linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable not used */
}
/*Create a suitable structure in C language for keeping the records of an employee of an
organization about their code, Name, Designation, Salary, department, city of posting.
Also write a program in C to enter the records of 100 employees and displays the name
of those who earn more than 20,000.*/

#include<stdio.h>
struct employee
{
int ecode;
char ename[20];
char designation[20];
int salary;
char dept[20];
char citypost[20];
}emp[100];
int main()
{
int i;

for(i=0;i<100;i++)
{
printf("Employee Code: ");
scanf("%d",&emp[i].ecode);
printf("Name : ");
scanf("%s",emp[i].ename);
printf("Designation : ");
scanf("%s",emp[i].designation);

printf("Salary : ");
scanf("%d",&emp[i].salary);
printf("Department : ");
scanf("%s",emp[i].dept);
printf("City of posting : ");
scanf("%s",emp[i].citypost);

printf("-----------------------------\n");
}
for(i=0;i<100;i++)
{
if(emp[i].salary>20000)
printf("%s\n",emp[i].ename);
}

return 0;
}
/*Define structure with syntax .Also write a program that compares two given dates. To
store date use structure say date that contains three members namely date, month and
year. If the dates are equal then display message as "Equal" otherwise "Unequal". */

#include<conio.h>
struct dmy
{
int date;
int month;
int year;
};

int main()
{
struct dmy a, b;
int flag;
printf("\nEnter the first date (dd mm yyyy) : ");
scanf("%d%d%d", &a.date, &a.month, &a.year);
printf("\nEnter the second date (dd mm yyyy) : ");
scanf("%d%d%d", &b.date, &b.month, &b.year);

if (a.date == b.date && a.month == b.month && a.year == b.year)

printf("\nThe dates are same\n");


else
printf("\nThe dates are not same\n");
getch();
return 0;
}

//Write a 'C' program to store the employee details using structure.

#include<stdio.h>
struct employee
{
int id,age,salary;
char name[25];
}emp[100];

void main()
{
int i,n;
printf("Enter the no of employees\n");
scanf("%d",&n);
printf("Enter employee info as id , name , age , salary\n");
for(i=0;i<n;i++)
{
printf("\nenter %d employee detail",i+1);
scanf("%d %s %d %d",&emp[i].id,emp[i].name,&emp[i].age,&emp[i].salary);
}
printf("\nEMP_NAME\tEMP_NAME\tEMP_AGE\t\tEMP_SAL\n");
for(i=0;i<n;i++)
{
printf("%d\t\t%s\t\t%d\t\t%d\n",emp[i].id,emp[i].name,emp[i].age,emp[i].salary);
}
}
/*Write a program in C using structure to enter and print the record of 100 books
available in your library. Following fields may be included in the record: -
book_title, book_price and number_of_pages. */

# include <stdio.h>
void linkfloat( ) ;
int main( )
{struct book
{
char book_title ;
float book_price ;
int number_of_pages ;
};
struct book b[ 100 ] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "Enter name, price and pages " ) ;
fflush ( stdin ) ;
scanf ( "%c %f %d", &b[ i ].book_title, &b[ i ].book_price, &b[ i ].number_of_pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "%c %f %d\n", b[ i ].book_title, b[ i ].book_price, b[ i ].number_of_pages ) ;
return 0 ;
}
void linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable not used */
}

/*Write a program in C to create a database of fifty students to store personal details such
as roll no, name and marks. Display the details of those students who secured marks
greater than 80.*/

#include <stdio.h>
struct student
{
char firstName[50];
int roll;
float marks;
} s[50];

int main() {
int i;
printf("Enter information of students:\n");

// storing information
for (i = 0; i < 50; ++i)
{
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");

// displaying information
for (i = 0; i < 50; ++i)
{
if(s[i].marks> 80)
{
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
}
return 0;
}

Other programs
1. Write a program to create a record of student that consist student name, rollno and
marks of a subject and age.
2. Write a program to create database of an employee (name,income) of an
organization. Print the name of an employee if his salary is greater than 20000
3. Write a program to create a record of 5 student that consist student name, rollno
and marks of a subject and age.

Array of structure

1. Write a program to create database of 20 students that include name, rollno, marks
in subject and display the detail and sum.
2. Write a program to create database of 20 students that include name, rollno, marks
in subject and display the detail of student to secured the higher marks..
3. Write a program to create database of Employees of an organization to print the
details of employees whose age is greater than 30 years and salary is greater than
15000

Union

It is the collection of different type of elements. It is a derived data type.


Both structures and unions are used to group a number of different variables together.
But while a structure enables us treat a number of different variables stored at
different places in memory, a union enables us to treat the same space in memory
as a number of different variables. That is, a union offers a way for a section of
memory to be treated as a variable of one type on one occasion, and as a different
variable of a different type on another occasion.

Memory representation of union:


Union student
{
char name[20];
int rollno;
float marks;
}
Here total 20 bytes allocated.
Here size of union is equal to the sizeof the largest number.
//program using union

# include <stdio.h>
int main( )
{
union a
{
short int i ;
char ch[ 2 ] ;
};
union a key ;
key.i = 512 ;
printf ( "key.i = %d\n", key.i ) ;
printf ( "key.ch[ 0 ] = %d\n", key.ch[ 0 ] ) ;
printf ( "key.ch[ 1 ] = %d\n", key.ch[ 1 ] ) ;
return 0 ;
}
output
key.i = 512
key.ch[ 0 ] = 0
key.ch[ 1 ] = 2

//program using union


# include <stdio.h>
int main( )
{
union a
{
short int i ;
char ch[ 2 ] ;
};
union a key ;
key.i = 512 ;
printf ( "key.i = %d\n", key.i ) ;
printf ( "key.ch[ 0 ] = %d\n", key.ch[ 0 ] ) ;
printf ( "key.ch[ 1 ] = %d\n", key.ch[ 1 ] ) ;
key.ch[ 0 ] = 50 ; /* assign a new value to key.ch[ 0 ] */
printf ( "key.i = %d\n", key.i ) ;
printf ( "key.ch[ 0 ] = %d\n", key.ch[ 0 ] ) ;
printf ( "key.ch[ 1 ] = %d\n", key.ch[ 1 ] ) ;
return 0 ;
}
key.i = 512
key.ch[ 0 ] = 0
key.ch[ 1 ] = 2
key.i= 562
key.ch[ 0 ] = 50
key.ch[ 1 ] = 2

difference between structure and union in reference of memory


struct a
{
short int i ;
char ch[ 2 ] ;
};
struct a key ;
This data type would occupy 4 bytes in memory, 2 for key.i and 1 each
for key.ch[ 0 ] and key.ch[ 1 ],

union a
{
short int i ;
char ch[ 2 ] ;
};
union a key ;
//write a program to create record of student using union
#include<stdio.h>
union student
{
char name[20];
int rollno;
float marks;
} u;
void main()
{
printf("enter name");
gets(u.name);
puts(u.name);
scanf("%d",u.rollno);
printf("%d",u.rollno);
scanf("%f",&u.marks);
printf("%f",u.marks);
}

Difference between structure and union


Structure

The struct keyword is used to define it. Union keyword is used to define it.

Sizeof struct will be equal to the sum of Size of union will be equal to the sizeof
sizeof each member. the largest member.

Each member has his unique memory All members has a common memory
space. A separate memory location is space. Only one member is active at a
assigned time . Single memory is allotted to all.

Change in one does not affect another. Change in one affects other entities.
All the members are active More memory efficient.
simultaneously. Less memory efficient.

Structure is faster in speed. Union is slower in speed.

Typedef

The typedef is a keyword that is used in C programming to provide existing data


types with a new name. typedef keyword is used to redefine the name already the
existing name.

typedef interpretation is performed by the compiler


typedef is limited to giving symbolic names to types only
typedef <existing_name> <alias_name>
typedef struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
} EMP ;
EMP e1, e2 ;
existing name: struct employee
alias: EMP
Enumeratetd Data Type

An enumerated type is an integer type with an associated set of symbolic constants


representing the valid values of that type.
The enumerated data type gives you an opportunity to invent your own data type and
define what values the variable of this data type can take.
//first part
enum mar_status
{
single, married, divorced, widowed
};
//second part
enum mar_status person1, person2 ;

The first part declares the data type and specifies its possible values. These values are
called ‘enumerators’..

The second part declares variables of this data type


person1 = married ;
person2 = divorced

The following expression would cause an error:


person1 = unknown ;

Internally, the compiler treats the enumerators as integers. Each value on the list of
permissible values corresponds to an integer, starting with 0. Thus, in our example,
single is stored as 0, married is stored as 1, divorced as 2 and widowed as 3.

//program on enum
# include <stdio.h>
# include <string.h>
int main( )
{
enum emp_dept
{
assembly, manufacturing, accounts, stores
};
struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
enum emp_dept department ;
};
struct employee e ;
strcpy ( e.name, "Lothar Mattheus" ) ;
e.age = 28 ;
e.bs = 5575.50 ;
e.department = manufacturing ;
printf ( "Name = %s\n", e.name ) ;
printf ( "Age = %d\n", e.age ) ;
printf ( "Basic salary = %f\n", e.bs ) ;
printf ( "Dept = %d\n", e.department ) ;
if ( e.department == accounts )
printf ( "%s is an accounant\n", e.name ) ;
else
printf ( "%s is not an accounant\n", e.name ) ;
return 0 ;
}

You might also like