Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Module 4 Structure and Union

Structures allow users to define custom data types that group related data. Structures can contain members of different data types and structures can be nested within other structures. Pointers can also be used to reference structure variables and access structure members indirectly through the pointer.

Uploaded by

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

Module 4 Structure and Union

Structures allow users to define custom data types that group related data. Structures can contain members of different data types and structures can be nested within other structures. Pointers can also be used to reference structure variables and access structure members indirectly through the pointer.

Uploaded by

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

Structures and unions

A structure is a user-defined data type which groups logically related items under one single unit.

All the different data items by accessing that single unit.

All the data item are stored in contiguous memory locations

The memory occupied by structure variable is the sum of sizes of all the members

It can store items of different data types

Structure definition syntax


struct_structure_name
{
data_type_variable_name;
data_type_variable_name;
........
data_type_variable_name;
}
Suppose we need to store the details of an employee. It includes ID, name, age, salary, designation
and several other factors which belong to different data types.

struct Empl
{
int emp_id;
float salary;
char designation[20];
int depart_no;
int age_of_emp;
};
Declaring structure variable

declare the structure variable by struct keyword

struct employee

{ int id;

char name[50];

float salary;

};
main()

{
struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure.
struct employee

{ int id;

char name[50];

float salary;

}e1,e2;
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
#include<stdio.h> //store second employee information

#include <string.h> e2.id=102;

struct employee strcpy(e2.name, "James Bond");

{ int id; e2.salary=126000;

char name[50];

float salary; //printing first employee information

}e1,e2; //declaring e1 and e2 variables for structure printf( "employee 1 id : %d\n", e1.id);

int main( ) printf( "employee 1 name : %s\n", e1.name);

{ printf( "employee 1 salary : %f\n", e1.salary);

//store first employee information

e1.id=101; //printing second employee information

strcpy(e1.name, "Sonoo Jaiswal");//copying string into printf( "employee 2 id : %d\n", e2.id);

char array printf( "employee 2 name : %s\n", e2.name);

e1.salary=56000; printf( "employee 2 salary : %f\n", e2.salary);

return 0;

}
#include <stdio.h>
struct stud
{
int roll;
char name[50];
float marks;
} s;
void main()
{
printf("Enter the name of student: ");
scanf("%s", s.name);
printf("Enter his/her roll number: ");
scanf("%d", &s.roll);
printf("Enter his/her marks: ");
scanf("%f", &s.marks);
printf("Displaying the Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %f\n", s.marks);
printf("\nEnter detailsof the Employee %d",i+1);
#include<stdio.h> printf("\n\tEnter Employee Id : ");
struct Employee
scanf("%d",&E[i].Id);
{
int Id; printf("\n\tEnter Employee Name : ");
int Age; scanf("%s",&E[i].Name);
char Name[25];
printf("\n\tEnter Employee Age : ");
long Salary;
}; scanf("%d",&E[i].Age);
void main() printf("\n\tEnter Employee Salary : ");
{
scanf("%ld",&E[i].Salary);
int i;
struct Employee E[ 3 ]; }
for(i=0;i<3;i++) printf("\nDetails of Eloyees");
{
for(i=0;i<3;i++)

{
printf("\n%d\t%s\t%d\t%ld",E[i].Id,E[i].Name,E[i].Age,E[i].Salary);

} }
Structures within a structure:

1. struct struct_name;
2. struct_name
The syntax to access the structure within another structure is:
3. {
4. data_type variable_name;
struct _variable. nested_struct_variable. struct_member;
5. struct struct_name
6. {
7. data_type variable_name;
8. ........
9. }struct_variable;
10. } variable_name;
1. struct employee
2. {
3. int emp_id;
e1.doj.day; -> for day in date
4. char name[20];
5. float salary; e1.doj.month; -> for month in date
6. int dept_no; e1.doj.year; -> for year in month
7. struct date
8. {
9. int day;
10. int month;
11. int year;
12. }doj;
13. }e1;
#include <stdio.h>
struct Emp
{
int id;
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
void main( )
{
e1.id=101;
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
printf( "employee id : %d\n", e1.id);
printf( "employee date of joining (dd-mm-yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
}
1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12. }emp;
13. void main ()
14. {
15. struct employee emp;
16. printf("Enter employee information?\n");
17. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
18. printf("Printing the employee information....\n");
19. printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
20. }
Operator in structure
operator is a member of the highest precedence group, this operator will take
precedence over the unary operators as well as the various arithmetic, relational,
logical and assignment operators.

\++variable. member is equivalent to ++( variable. member) ;


struct date
{
int month ;
int day ;
int year;
};
struct account {
int acct-no;
char acct-type;
char name[80];
float balance ;
struct date lastpayment;
} customer;
The last member of customer is customer. lastpayment, which is itself a structure of
type date. To access the month of the last payment,
Customer.lastpayment.month
this value can be incremented by writing
++customer.lastpayment.month
Array of Structures

customer is an array that may contain as many as 100 elements.

Each element is a structure of type account.

if we wanted to access the account number for the 14th customer , write as
customer[ 13] .acct_no.

customer's balance can be accessed by writing customer[ 13]. balance.


Updating Customer Records
https://docs.google.com/document/d/1eH4-ggPCbGH1aXAEF9rQwRyMFDmGhje
s/edit?usp=drive_link&ouid=110716732594862403266&rtpof=true&sd=true
USER-DEFINED DATA TYPES (typedef)
a new data type is defined as

typedef type new- type;

where type refers to an existing data type

new- type refers to the new user-defined data type.


typedef int age;

In this declaration age is a user-defined data type, which is equivalent to type int.

age male, female;

is equivalent to writing

int male, female;


typedef f loat height[ 100];

height men, women;

define height as a 100-element, floating-point array type-hence, men and women


are 100-element, floating-point arrays.
The first declaration defines record as a user-defined data type.
The second declaration defines oldcustomer and newcustomer as structure
variables of type record.
STRUCTURES AND POINTERS
The beginning address of a structure can be accessed in the same manner as any
other address, through the use of the address (&) operator.

if variable represents a structure-type variable, then &variable represents the


starting address of that variable.

type *ptvar;

where type is a data type that identifies the composition of the structure, and ptvar
represents the name of the pointer variable

ptvar = &variable;
typedef struct
{
int acct-no;
customer is a structure variable of type account,
char acct-type;
and pc is a pointer variable whose object is a
char name[bO]; structure variable of type account.
the beginning address of customer can be assigned
float balance;
to pc by writing
} account; pc = &customer;
account customer, *pc;
pointer variable pc is initialized by
assigning it the beginning address of the
structure variable customer. pc will
point to customer.

to access the customer’s account number,


any of the following:

Customer.acct-no

pc->acct-no

(*pc).acct-no
customer's balance can be accessed by writing any of the following:
customer.balance pc->balance (*pc).balance

the customer's name can be accessed by writing any of the following: customer.
name pc ->name (*pc).name
#include <stdio.h>
int main( )
{
int n = 3333;
char t = 'C';
float b = 99.99;
typedef struct {
int month;
int day;
int year;
} date;
struct {
int *acct_no;
char *acct_type;
char *name;
float *balance;
date lastpayment;
} customer, *pc = &customer;
customer.acct_no = &n;
customer.acct_type = &t;
customer.name ="Smith";
customer.balance = &b;
printf("%d %c %s %.2f\n", *customer.acct_no, *customer.acct_type,customer.name, *customer.balance);
printf("%d %c %s %.2f\n", *pc->acct_no, *pc->acct_type, pc->name, *pc->balance);
}
PASSING STRUCTURES TO FUNCTIONS
To pass structure-type information to or from a function,

Structure members can be transferred individually, or entire structures can be


transferred.
Individual structure members can be passed to a function as arguments in the
function call, and a single structure member can be returned via the return
statement.
customer. name, customer. acct-no and customer. balance are passed to the function
ad just.

Within ad just, the value assigned to newbalance presumably makes use of the
information passed to the function.

This value is then returned to main, where it is assigned to the structure member
customer. balance.
SELF-REFERENTIAL STRUCTURES
within a structure one member that is a pointer to the parent structure type.

where name refers to the name of a


pointer variable. Thus, the structure
of type tag will contain a member
that points to another structure of
type tag. Such structures are known
as self-referential structures.

Self-referential structures are very useful in applications that involve


linked data structures, such as lists and trees.
Unions

A union is declared and used in the same ways that a structure. Unions are defined
and declared in the same fashion as structures.

In unions, all the members share the space which is according to the space
requirement of the largest member.

The union can hold only one value at a time.

A union can be initialized on its declaration. Because only one member can be used
at a time, only one can be initialized.

To avoid confusion, only the first member of the union can be initialized.
Union Data Type

A union is a user defined data type like structure.

The union groups logically related variables into a single unit.

The union data type allocates the space equal to space needed to hold the largest
data member of union.

The union allows different types of variable to share same space in memory.

There is no other difference between structure and union than internal difference.
The method to declare, use and access the union is same as structure.
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
#include<stdio.h>
union job
{ char name[32];
float salary;
int worker_no;
} u;
struct job1
{ char name[32];
float salary;
int worker_no;
} s;
void main( )
{ printf("size of union = %d", sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
}

You might also like