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

Structure & Unions

Structures allow you to define a custom data type that combines data of different types under one name. This allows grouping together related data such as the title, author, subject, and ID of a book. Structures are defined using the struct keyword followed by the structure tag name and members. Structure variables can then be declared, and individual members accessed using the dot operator. Arrays of structures can also be defined, with each element of the array representing a structure variable. Structures can be passed to functions by value or by reference.

Uploaded by

Owimark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Structure & Unions

Structures allow you to define a custom data type that combines data of different types under one name. This allows grouping together related data such as the title, author, subject, and ID of a book. Structures are defined using the struct keyword followed by the structure tag name and members. Structure variables can then be declared, and individual members accessed using the dot operator. Arrays of structures can also be defined, with each element of the array representing a structure variable. Structures can be passed to functions by value or by reference.

Uploaded by

Owimark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

4/13/2022

Structure C arrays allow you to define type of variables


that can hold several data items of the same kind
but structure is another user defined data type
available in C programming, which allows you to
combine data items of different kinds.
Structures are used to represent a record,
Suppose you want to keep track of your books in a
library. You might want to track the following
attributes about each book:
Title
Author
Subject
Book ID

Defining a Structure
To define a structure, you must use struct Books
the struct statement.
{
struct [structure tag]
{ member definition; char title[50];
member definition; char author[50];
... char subject[100];
member definition; int book_id;
} [one or more structure variables];
} book;
The structure tag is optional and each member
definition is a normal variable definition, such as
int i; or float f; or any other valid variable
definition. At the end of the structure's definition,
before the final semicolon, you can specify one or
more structure variables but it is optional.

Declaring Structure Variables


It is possible to declare variables of 1) Declaring Structure variables separately
a structure, after the structure is struct Student
defined. Structure variable declaration is
{
similar to the declaration of variables of any
other data types. Structure variables can be char name[20];
declared in following two ways. int age;
int rollno;
} ;
struct Student S1 , S2; //declaring variables of
Student

1
4/13/2022

Accessing Structure Members


2) Declaring Structure Variables with Structure To access any member of a structure, we use
definition the member access operator (.). The member access
struct Student operator is coded as a period between the
structure variable name and the structure member
{
that we wish to access. You would
char[20] name; use struct keyword to define variables of
int age; structure type. Following is the example to
int rollno; explain usage of structure:
} S1, S2 ;

Structure Initialization
struct Book struct Patient
{ {
char name[15]; float height;
int price; int weight;
int pages; int age;
} b1 , b2 ; };
b1.price=200; //b1 is variable of Book type and struct Patient p1 = { 180.75 , 73, 23 };
price is member of Book //initialization or,
We can also use scanf() to give values to struct patient p1;
structure members through terminal. p1.height = 180.75; //initialization of each
scanf(" %s ", b1.name); member separately
scanf(" %d ", &b1.price); p1.weight = 73;
p1.age = 23;

struct employee
Array of Structure {
char ename[10];
We can also declare an array of structure. Each
element of the array representing int sal;
a structure variable. }emp[5];
Example : struct employee emp[5]; void ask()
The above code define an array emp of size 5 {
elements. Each element of array emp is of int i,j;
type employee for(i=0;i<3;i++)
{
printf("\nEnter %d employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);

2
4/13/2022

printf("\nEnter employee salary\t");


Nested Structures
scanf("%d",&emp[i].sal);
} struct student
printf("\nDisplaying Employee record\n"); {
for(i=0;i<3;i++) char name[30];
{ int age;
printf("\nEmployee name is %s",emp[i].ename); struct address
printf("\nSlary is %d",emp[i].sal); {
} } char locality[40];
void main() char city[40];
{ int pincode;
clrscr(); };
ask(); };
getch();
}

Keyword typedef while using


structure
Structure as function arguments
typedef struct complex 1) Passing structure by value
{ 2) Passing structure by reference
int imag;
float real;
}comp;
Inside main:
comp c1,c2;
Here, typedef keyword is used in creating a
type comp(which is of type as struct complex).
Then, two structure variables c1 and c2 are
created by this comp type.

struct student
{
Passing structure by value char name[50];
int roll;
A structure variable can be passed to the };
function as an argument as normal variable. void Display(struct student std); /* function
If structure is passed by value, change made in prototype should be below to the structure declaration
structure variable in function definition does otherwise compiler shows error */
not reflect in original structure variable in int main()
calling function. {
struct student s1;
printf("Enter student's name: ");
scanf("%s",s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as
argument
return 0; }

3
4/13/2022

void Display(struct student std) Enter student's name: Kevin Amla


{ Enter roll number: 149
printf("Name: %s",std.name); Name: Kevin Amla
printf("\nRoll: %d",std.roll); Roll: 149
}

struct distance
{
Passing structure by reference
int feet;
The address location of structure variable is float inch;
passed to function while passing it by reference. };
If structure is passed by reference, change made void Add(struct distance d1,struct distance d2, struct
in structure variable in function definition distance *d3);
reflects in original structure variable in the int main()
calling function. {
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");

void Add(struct distance d1,struct distance d2,


struct distance *d3)
{
printf("Enter feet: ");
/* Adding distances d1 and d2 and storing it in
scanf("%d",&dist2.feet);
d3 */
printf("Enter inch: ");
d3->feet=d1.feet+d2.feet;
scanf("%f",&dist2.inch);
d3->inch=d1.inch+d2.inch;
Add(dist1, dist2, &dist3);
if (d3->inch>=12)
/*passing structure variables dist1 and dist2 by
{
value whereas passing structure variable dist3 by
reference */ /* if inch is greater or equal to 12, converting
it to feet. */
printf("\nSum of distances = %d\'-
%.1f\"",dist3.feet, dist3.inch); return 0; d3->inch-=12;
} ++d3->feet;
}
}

4
4/13/2022

Pointers to Structures
Output: struct Books *struct_pointer;
First distance Now, you can store the address of a structure
Enter feet: 12 variable in the above defined pointer variable.
To find the address of a structure variable,
Enter inch: 6.8
place the & operator before the structure's name
Second distance as follows:
Enter feet: 5 struct_pointer = &Book1;
Enter inch: 7.5 To access the members of a structure using a
Sum of distances = 18'-2.3“ pointer to that structure, you must use the ->
operator as follows:
struct_pointer->title;

struct name scanf("%f",&(*ptr).b);


{ printf("Displaying: ");
int a; printf("%d%f",(*ptr).a,(*ptr).b);
float b; return 0;
};
}
int main()
{
struct name *ptr, p;
ptr=&p;
/* Referencing pointer to memory address of p */
printf("Enter integer: ");
scanf("%d",&(*ptr).a);
printf("Enter number: ");

The pointer variable of type struct name is Accessing structure member through pointer using
referenced to the address of p. Then, only the dynamic memory allocation
structure member through pointer can accessed. To access structure member using pointers, memory
Structure pointer member can also be accessed can be allocated dynamically using malloc()
using -> operator function defined under "stdlib.h" header file.
(*ptr).a is same as ptr->a Syntax to use malloc()
(*ptr).b is same as ptr->b ptr=(cast-type*)malloc(byte-size)

5
4/13/2022

Accessing structure's member


through pointer using malloc()
malloc() /* Above statement allocates the memory for n
function structures with pointer ptr pointing to base address
struct name */
{ for(i=0;i<n;i++)
int a; {
float b; printf("Enter string, integer and floating number
char c[30]; respectively:\n");
}; scanf("%s %d %f",&(ptr+i)->c, &(ptr+i)->a, &(ptr+i)-
int main() >b);
{ }
struct name *ptr; printf("Displaying Infromation:\n");
int i,n; for(i=0;i<n;++i)
printf("Enter n: "); printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)-
>b);
scanf("%d",&n);
return 0;
ptr=(struct name*)malloc(n*sizeof(struct name));
}

Unions
Enter n: 2 A union is a special data type available in C
that enables you to store different data types in
Enter string, integer and floating number
the same memory location.
respectively:
You can define a union with many members, but
Programming 2 3.2 only one member can contain a value at any given
Enter string, integer and floating number time.
respectively: Like structure, Union in c language is a user
Structure 6 2.3 defined datatype that is used to hold different
type of elements.
Displaying Information
But it doesn't occupy sum of all members size. It
Programming 2 3.20 occupies the memory of largest member only. It
Structure 6 2.30 shares memory of largest member.

Defining a Union
Advantage of union over structure To define a union, you must use
It occupies less memory because it occupies the the union statement in very similar was as you
memory of largest member only. did while defining structure.
Disadvantage of union over structure The union statement defines a new data type, with
It can store data in one member only. more than one member for your program.
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];

6
4/13/2022

union Data When the above code is compiled and executed, it


{ produces the following result:
int i; Memory size occupied by data : 20
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n",
sizeof(data));
return 0;
}

Accessing Union Members


To access any member of a union, we use union Data
the member access operator (.). {
The member access operator is coded as a period int i;
between the union variable name and the union
float f;
member that we wish to access.
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); Output:


printf( "data.f : %f\n", data.f); data.i : 1917853763
printf( "data.str : %s\n", data.str); data.f: 412236058.000000
return 0; data.str : C Programming
} Here, we can see that values of i and f members
of union got corrupted because final value
assigned to the variable has occupied the memory
location and this is the reason that the value
if str member is getting printed very well.

7
4/13/2022

union Data
{
int i;
float f; Output:
char str[20];
data.i : 10
};
data.f : 220.500000
int main( )
data.str : C Programming
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}

Difference between union and


structure
union job int main()
{ {
char name[32]; printf("size of union = %d",sizeof(u));
float salary; printf("\nsize of structure = %d", sizeof(s));
int worker_no; return 0;
}u; }
struct job1
{
char name[32];
float salary;
int worker_no;
}s;

Output
size of union = 32
size of structure = 40

8
4/13/2022

union job
{
char name[32];
But, the memory required to store a union
variable is the memory required for largest float salary;
element of an union. int worker_no;
}u;
int main()
{
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %f",u.salary);
return 0; }

Why this output?


Output Initially, Hillary will be stored in u.name and
Enter name Hillary other members of union will contain garbage
value. But when user enters value of salary,
Enter salary 1234.23
1234.23 will be stored in u.salary and other
Displaying Name: f%Bary members will contain garbage value. Thus in
Salary: 1234.23 output, salary is printed accurately but, name
displays some random string.

You might also like