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

Structures and Unions

The document provides an overview of structures and unions in C programming, detailing their definitions, initialization, memory allocation, and usage. It explains how to define structures, access their members, and the differences between structures and unions, including memory sharing. Additionally, it covers nested structures, arrays of structures, pointers, self-referential structures, and provides examples of each concept.

Uploaded by

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

Structures and Unions

The document provides an overview of structures and unions in C programming, detailing their definitions, initialization, memory allocation, and usage. It explains how to define structures, access their members, and the differences between structures and unions, including memory sharing. Additionally, it covers nested structures, arrays of structures, pointers, self-referential structures, and provides examples of each concept.

Uploaded by

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

Week 14 – Structures and Unions

STRUCTURES

-Need for structures?

Definition :

A Structure is a collection of variables of different data types under a single name.

ie A Structure is a collection of dissimilar data items.

•It is a user defined data type.

Defining a structure

struct structure_name

datatype element1;

datatype element2;

datatype elementN;

};

struct structure_name var1, var2;

struct structure_name

datatype element1;

datatype element2;

datatype elementN;

} var1, var2;
Example

struct student

char grades;

int rno;

float avg;

};

struct student s1;

struct student

char grades;

int rno;

float avg;

}s1;

Initialization of a structure

struct student

int rno;
int tot;

float avg;

};

struct student s1={101, 486, 97.20};

struct student

int rno;

int tot;

float avg;

}s1={101, 486,97.20};

#include <stdio.h>

int main() {

struct student

char grades;

int rno;

float avg;

}s1;

printf("%d",sizeof(s1));

return 0;

The amount of the memory space allocated to it is equal to the sum of the memory space required
by all of its members.

struct student

char grades;

int rno;

float avg;

}s1;
Size of the structure =12 bytes

(4+4+4)

struct student

char name[20];

int tot;

float avg;

}s1;

Size of the structure = 28 bytes

(20+4+4)

Referencing structure elements

struct student

int rno;

float avg;

}s1,s2;

The structure members are accessed as,

s1.rno, s1.avg and

s2.rno, s2.avg;

⇨ It uses dot operator with syntax is,

⇨ Structure_variable . member_name

/* Simple example using structures */

#include<stdio.h>

int main()

struct student

char name[20];
int rno;

};

struct student s1;

printf("Enter Name, Rollno \n");

scanf("%s%d",s1.name,&s1.rno);

printf("\n name and roll no is ")

printf("%s %d",s1.name, s1.rno);

Nested Structures

struct namelist

char fname[20];

char lname[10];

};

struct phonebook

struct namelist name;

char mobile[15];

};

struct phonebook p1;

mobile ------------🡪 p1.mobile

fname ----------🡪 p1.name.fname

Array of Structures

• An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities.

• The array of structures in C are used to store information about multiple entities of different data
types.

• The array of structures is also known as the collection of structures.

struct student

{
int rno;

float avg;

}s[50];

• In such cases the structure elements are accesses with for loop as s[i].rno,s[i].avg

• ie for(i=0;i<50;i++)

• scanf(“%d %f ” ,&s[i].rno,&s[i],avg);

/* example using array of structures.

#include<stdio.h>

struct student

char name[20];

int rno;

};

int main()

struct student s[65];

int n,i;

printf("Enter the number of students \n");

scanf("%d",&n);

printf("Enter Name, Rollno of students\n");

for(i=0;i<n;i++)

scanf("%s%d",s[i].name,&s[i].rno);

printf("\n The student details are:\n");

for(i=0;i<n;i++)

printf("\n %s %d",s[i].name,s[i].rno);
}}

#include<stdio.h>

struct student

int rno;

int tot;

float avg;

};

main()

struct student s1={101,426,85.20};

struct student s2;

s2=s1;

printf("%d%d%f",s1.rno,s1.tot,s1.avg);

printf("%d%d%f",s2.rno,s2.tot,s2.avg);

output: 101 426 85.60

101 426 85.60

Structure as Function Arguments

• We can pass a structure as a function argument just like we pass any other variable or an array as a

function argument.

#include<stdio.h>

struct Student

char name[10];

int roll;

};

void show(struct Student); /* function declaration */


int main()

struct Student std;

printf("\nStudent name, roll no:\n");

scanf("%s%d", std.name, &std.roll);

show(std); /* function call */

void show(struct Student st) /* function definition */

printf("\nstudent name is %s", st.name);

printf("\nroll is %d", st.roll);

Pointers to structures

• It is possible to create a pointer to a structure type. It can store the address of a structure variable.

struct stud

……….

……….

}s1,*s2; s1 -> structure variable

s2=&s1; s2-> structure pointer

#include<stdio.h>

struct student

int rno;

float tot;

};

int main()
{

struct student s1={101,95};

struct student *s2;

s2=&s1;

printf("\n %d %f",s1.rno,s1.tot);

printf("\n %d %f",s2->rno,s2->tot);

return 0;

Output:

101 95.000000

101 95.000000

Self Referential Structure

• Self Referential Structure is the Data Structure in which the pointer refers (points) to the structure
of the same type. It used in the many of the data structures like in Linked List, Trees, Graphs, Heap
etc.

Example:

struct node

int data;

struct node *link;

}newnode;

Here, the members are accessed using -> (arrow) operator as follows

newnode->data;

newnode->link;

Union

• Like structure, Union in c language is a user-defined data type that is used to store the different
type of elements.

• All the aspects and the operations of union are same that of structures. The only difference
between them is in terms of storage of their memories.
• In structure, a separate memory is allotted to each member, while in unions, all the members of an
object share the same memory.

• The size of a union is equal to the size of the largest data member.

Initialization of Unions

union object can hold the value of only one of its member at a time. Hence while initializing a union
object, it is allowed to initialize its first member only.

union student

{ int rno;

int m1,m2,m3;

float avg;

};

union student s={101};


/* Simple example using union */

#include<stdio.h>

int main()

union student

char name[20];

int rno;

};

union student s1;

printf("Enter Name\n");

scanf("%s",s1.name);

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

printf("\nEnter roll no\n");

scanf("%d",&s1.rno);

printf("\nroll no is %d",s1.rno);

/*student details using union */

#include<stdio.h>

union student

char name[20];

int rno,m1,m2,m3,tot;

float avg;

};

int main()

union student s[60];


int n,i,j,temp=0;

printf("Enter the number of students\n");

scanf("%d",&n);

printf("Enter Name, Regno, 3 marks of %d students\n",n);

for(i=0;i<n;i++)

scanf("%s",s[i].name);

printf("Name %s\t",s[i].name);

scanf("%d",&s[i].rno);

printf("Rollno %d\t",s[i].rno);

scanf("%d",&s[i].m1);

printf("Mark 1 %d\t",s[i].m1);

temp=s[i].m1;

scanf("%d",&s[i].m2);

printf("Mark 2 %d\t",s[i].m2);

temp=temp+s[i].m2;

scanf("%d",&s[i].m3);

printf("Mark 3 %d\t",s[i].m3);

temp=temp+s[i].m3;

s[i].tot=temp;

printf("Total %d\n",s[i].tot);

s[i].avg=temp/3;

printf("Average %f\n",s[i].avg);

Comparison between Structure and Union

Structure union

Structure is a collection of elements of Union is a collection of elements of different

different data type under a single name. data type under a single name.
Declared with the keyword struct followed Declared with the keyword union followed by

by structure name and set of elements union name and set of elements

Each member has its own storage space All the members share the same memory

space to store the values

It can handle all the members at the same It can handle only one element at a time

time

Example

struct student union student

{ char grade; { char grade;

int rno; int rno;

float avg; float avg;

} s; } s;

size of the above structure is 9 size of the union is 4 bytes [ maximum sized

bytes[1+4+4] element]

More storage space is required. Less storage space is required.

It may be initialized with all its members

Example struct stud

{ int rno;

float avg;

};

struct stud s={101,95.50};

Only its first member may be initialized

union stud

{ int rno;

float avg;

};

union stud s={101}; (only 1st element)


Ans: D

Ans: A
Ans: B

Ans: B
Ans: A
Ans: A
Ans: B

#include<stdio.h>

int main()

struct num

int i, j, k, l;

};

struct num n = {1, 2, 3};

printf("%d %d %d %d", i, j, k, l);

(Compilation error)
#include<stdio.h>

struct

int i;

float ft;

}decl;

int main()

decl.i = 4;

decl.ft = 7.96623;

printf("%d %.2f", decl.i, decl.ft);

return 0;

Output: 4 7.97

#include<stdio.h>

int main()

struct leader

char *lead;

int born;

};

struct leader l1 = {"AbdulKalam", 1931};

struct leader l2 = l1;

printf("%s %d", l2.lead, l1.born);

Output: AbdulKalam 1931

#include<stdio.h>
int main()

struct st

int i;

static int si;

};

struct st s = {1, 2};

printf("%d %d", s.i, s.si);

return 0;

(Compilation error)

You might also like