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

Modue4 Lect1,2,3,4

- A structure allows combining data of different types under a single name. It defines a new data type with defined members. - To define a structure, the struct keyword is used followed by the structure tag name. Members of different types can then be defined. - Structure members are accessed using the dot (.) operator by specifying the structure variable name and member name.

Uploaded by

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

Modue4 Lect1,2,3,4

- A structure allows combining data of different types under a single name. It defines a new data type with defined members. - To define a structure, the struct keyword is used followed by the structure tag name. Members of different types can then be defined. - Structure members are accessed using the dot (.) operator by specifying the structure variable name and member name.

Uploaded by

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

Structure

• Arrays hold several data items of the same kind.


• Structure is a collection of variables of different
types under a single name.
• Structure is another user defined data type
available in C that allows to combine data items
of different kinds.
• Each element in a C structure is called member.
Syntax of structure
• Keyword struct is used for creating a structure.
• The struct statement defines a new data type, with more than one member.

struct tagname{

member1 definition;
member2 definition;
...
membern definition;
} [one or more structure variables];

• struct is the keyword.


• tagname specifies the name of a structure
• member1, member2 specifies the data items that makeup structure.
Create a Structure
struct Books// structure declaration
{
char title[50]; // Member char array
char author[50]; // Member char array
char subject[100]; // Member char array
int book_id; // Member (int variable)
}; // End the structure with a semicolon
What we know is that size of a struct is the sum of all the data members?
Like for the following struct,
struct A{
int a;
int* b;
char c;
char *d;
};
Now considering the 64-bit system,
Size of int is 4 Bytes
Size of character is 1 Byte
Size of any pointer type is 8 Bytes
(Pointer size doesn't depend on what kind of data type they are pointing
too)

So the size of the struct should be: (4+8+1+8)=21 Bytes


Let's see what compiler is giving using the sizeof() operator.
#include <stdio.h>

struct A
{
int a;
int* b;
char c;
char* d;
};

int main()
{
struct A a;
printf("Size of struct A: %lu\n", sizeof(struct A));
printf("Size of object a: %lu\n", sizeof(a));
return 0;
}
Output
Size of struct A: 32
Size of object a: 32 //instead of 21 bytes compiler gives 32 bytes as answer
Structure Padding
• To find the actual size, you need to understand two concepts of padding
• Processor doesn't read 1byte at a time from memory. It reads 1 word at a
time. In 32 bit processor, it can access 4 bytes at a time which means word
size is 4 bytes.
• Similarly in a 64 bit processor, it can access 8 bytes at a time which means
word size is 8 bytes.
• So in previous example, It aligns till the boundary of maximum memory
allocated.
• Here we find that max memory allocated is 8 Bytes, thus all the data
members acquire 8 Bytes and the total size is 32 Bytes.
Example for structure Padding
struct B { Output:
int* b; Size of struct B: 24
char c; Size of object b: 24
int a;
char* d;
};

int main()
{
struct B b;
printf("Size of struct B: %lu\n",
sizeof(struct B));
printf("Size of object b: %lu\n",
sizeof(b));
return 0;
}
#include<stdio.h> #include<stdio.h>
struct book
struct book {
{ double issno ;
double price ;
double issno ; int volumeno;
double price ; };
main( )
double volumeno; {
}; struct book b1;
main( )
printf("\n the sizeof the structure is
{ %d",sizeof(b1));
struct book b1; }
Output (here padding takes place)
printf("\n the sizeof the structure is
%d",sizeof(b1));
}
Accessing the members of a Structure
• To access the structure, you must create a variable of
it.
• Use the struct keyword inside the main() method,
followed by the name of the structure and then the
name of the structure variable
Structure variable declaration
struct person struct person
{
char name[50];
{
int age; char name[50];
float salary; int age;
};
float salary;
int main() } person1, person2;
{
struct person person1,
person2;
return 0;
}
Accessing members of a structure
• There are two types of operators used for accessing
members of a structure.
– Member operator(.)
– Structure pointer operator(->)

• Any member of a structure can be accessed as:

structure_variable_name.member_name

• Suppose, we want to access the age of the struct


variable person2. Then, it can be accessed as:

person2.age
Example Program
strcpy( Book2.title, "Telecom Billing");
#include <stdio.h> strcpy( Book2.author, "Zara Ali");
#include <string.h>
strcpy( Book2.subject, "Telecom Billing
struct Books { Tutorial");
char title[50]; Book2.book_id = 6495700;
char author[50]; printf( "Book 1 title : %s\n", Book1.title);
char subject[100]; printf( "Book 1 author : %s\n",
long int book_id; Book1.author);
}; printf( "Book 1 subject : %s\n",
Book1.subject);
int main( )
{ printf( "Book 1 book_id : %d\n",
struct Books Book1; Book1.book_id);
struct Books Book2; printf( "Book 2 title : %s\n", Book2.title);
strcpy( Book1.title, "C Programming"); printf( "Book 2 author : %s\n",
strcpy( Book1.author, "Nuha Ali"); Book2.author);
strcpy( Book1.subject,"C printf( "Book 2 subject : %s\n",
Programming”); Book2.subject);
Book1.book_id = 6495407; printf( "Book 2 book_id : %d\n",
Book2.book_id);
return 0;}
Initialize structure members
• Structure members cannot be initialized with declaration. For
example the following C program fails in compilation.

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
}
Initialization of structure variables

struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 };


Initialization of structure variables

struct book
{
char name[10] ;
float price ;
int pages ;
};
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;
#include <stdio.h>
#include <string.h>

struct Employee
{
char name[20];
char gender;
int empid;
};
void main()
{
struct Employee emp={"Anny",'f',15698};
printf("\n the employee name is %s and gender is %c and emp id
is %d",emp.name,emp.gender,emp.empid);
}
Designated Initialization allows structure members to
be initialized in any order.
#include <stdio.h>
#include <string.h>
struct Employee
{
char name[20];
char gender;
int empid;
};
void main()
{
struct Employee emp={.gender='f',.name="Anny",.empid=15698};
printf("\n the employee name is %s and gender is %c and emp id is
%d",emp.name,emp.gender,emp.empid);
}
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
} record;

int main()
{

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
Array of Structure
• We can also declare an array of structure
variables, in which each element of the array
will represent a structure variable.

Example : struct employee emp[5];


Array of structure Example
#include<stdio.h> for(i = 0; i < 3; i++)
{
struct Employee printf("\nEnter %dst Employee
{ record:\n", i+1);
char ename[10]; printf("\nEmployee name:\t");
int sal; scanf("%s", emp[i].ename);
}; printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}

int main() printf("\nDisplaying Employee record:\n");


{ for(i = 0; i < 3; i++)
struct Employee emp[5]; {
int i, j; printf("\nEmployee name is %s",
emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
return 0;
}
Nested Structures
• Structure written inside another structure is
called as nesting of two structures.
• Nested Structures are allowed in C Programming
Language.
• We can write one Structure inside another
structure as member of another structure.
Example for nested Structure
struct date • Accessing Month Field :
{
int day; emp1.doj.month
int month; • Accessing day Field :
int year; emp1.doj.day
};
• Accessing year Field :
struct Employee emp1.doj.year
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
Initialization of nested Structure with values

main( ) struct emp


{ {
struct address char name[25] ;
{ struct address a ;
char phone[15] ;
};
char city[25] ;
struct emp e = { "jeru", "531046", "nagpur", 10 };
int pin ;
};
printf ( "\n name = %s phone = %s", e.name, e.a.phone ) ;
printf ( "\ncity = %s pin = %d", e.a.city, e.a.pin ) ; }

output
name = jeru phone = 531046
city = nagpur pin = 10
#include <stdio.h> scanf("%f",&b1.price);
struct author printf("\n enter the author details, name:");
scanf("%s",b1.details.aname);
{ printf("\n enter the no of pages in the book");
char aname[20]; scanf("%d",&b1.details.pages);
int pages; printf("\n details....");
}; printf("\n Book name:%s",b1.name);
printf("\n Book price:%f",b1.price);
printf("\n Author name:%s",b1.details.aname);
struct book printf("\n No of pages:%d",b1.details.pages);
{ }
char name[10] ; Output
float price ;
struct author details;
};

void main()
{
struct book b1,b2;
printf("\n enter the name of the book
");
scanf("%s",b1.name);
printf("enter the price details:");
#include <stdio.h>
struct author for(i=0;i<n;i++)
{
char aname[20];
{
int pages; printf("\n details of
};
book%d",i+1);
struct book printf("\n Book
{
char name[10] ; name:%s",b1[i].name);
float price ; printf("\n Book
struct author details;
}; price:%f",b1[i].price);
void main()
{
printf("\n Author
struct book b1[10]; name:%s",b1[i].details.aname);
int n,i;
printf("\n enter how many book details are you
printf("\n No of
going to collect"); pages:%d",b1[i].details.pages);
scanf("%d",&n);
for(i=0;i<n;i++) }
{ }
printf("\n enter the name of the book%d",i+1);
scanf("%s",b1[i].name);
printf("enter the price details:");
scanf("%f",&b1[i].price);
printf("\n enter the author details, name:");
scanf("%s",b1[i].details.aname);
printf("\n enter the no of pages in the book");
scanf("%d",&b1[i].details.pages);
}
To search for a book in the list
#include <stdio.h> for(i=0;i<n;i++)
#include <string.h>
struct author
{
{ printf("\n details of book%d",i+1);
char aname[20]; printf("\n Book name:%s",b1[i].name);
int pages; printf("\n Book price:%f",b1[i].price);
};
printf("\n Author name:%s",b1[i].details.aname);
struct book printf("\n No of pages:%d",b1[i].details.pages);
{ }
char name[10] ; printf("\n enter the name of the books which u
float price ; want to search");
struct author details;
};
fflush(stdin);
void main() scanf("%s",Sbook);
{ for(i=0;i<n;i++)
struct book b1[10]; {
int n,i;
int flag=0;
if(strcmp(b1[i].name,Sbook)==0)
char Sbook[20]; {
printf("\n enter how many book details are you going to flag=1;
collect"); break;
scanf("%d",&n);
for(i=0;i<n;i++)
}
{ }
printf("\n enter the name of the book%d",i+1); if (flag==1)
scanf("%s",b1[i].name); printf("\n the book is found");
printf("enter the price details:");
scanf("%f",&b1[i].price);
else
printf("\n enter the author details, name:"); printf("\n book is not found");
scanf("%s",b1[i].details.aname); }
printf("\n enter the no of pages in the book");
scanf("%d",&b1[i].details.pages);
}
Output
enter how many book details are you going to collect2

enter the name of the book1C


enter the price details:900

enter the author details, name:yashwant

enter the no of pages in the book1000

enter the name of the book2Java


enter the price details:450

enter the author details, name:Herbert

enter the no of pages in the book100

details of book1
Book name:C
Book price:900.000000
Author name:yashwant
No of pages:1000
details of book2
Book name:Java
Book price:450.000000
Author name:Herbert
No of pages:100
enter the name of the books which u want to searchC

the book is found


Process returned 19 (0x13) execution time : 27.693 s
Press any key to continue.
Another Syntax: Nested Structure
#include <stdio.h> printf("enter the price details:");
#include <string.h> scanf("%f",&b1[i].price);
struct book printf("\n enter the author details, name:");
{ scanf("%s",b1[i].details.aname);
char name[10] ; printf("\n enter the no of pages in the book");
float price ; scanf("%d",&b1[i].details.pages);
struct author }
{ for(i=0;i<n;i++)
char aname[20]; {
int pages;
printf("\n details of book%d",i+1);
}details;
printf("\n Book name:%s",b1[i].name);
}b1[10];
printf("\n Book price:%f",b1[i].price);
void main()
printf("\n Author name:%s",b1[i].details.aname);
{
int n,i; printf("\n No of pages:%d",b1[i].details.pages);
int flag=0; }
printf("\n enter how many book details are you }
going to collect");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter the name of the book%d",i+1);
scanf("%s",b1[i].name);
• Output of program - slide 30
Structures 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> void main()
struct Student {
{ struct Student std;
char name[10]; printf("\nEnter Student record:\n");
int roll; printf("\nStudent name:\t");
}; scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
//function prototype declaration scanf("%d", &std.roll);
void show(struct Student st); show(std);
}

void show(struct Student st)


{
printf("\n student name is %s", st.name);
printf("\n roll is %d", st.roll);
}
/* Passing individual structure elements */

#include<stdio.h> display(int a, int b, int c)


{
struct date{
printf("day = %d ", a);
int day; printf("month = %d ",b);
int mon; printf("year = %d ",c);
}
int yr;
};
Output
main ( )
{ day = 2
month = 1
struct date d= {02,01,2010};
year = 2010
display(d.day, d.mon, d.yr);
}
Structure using Pointer
• C structure can be accessed in 2 ways in a C
program. They are,
– Using normal structure variable
– Using pointer variable

• Dot(.) operator is used to access the data


using normal structure variable and arrow (->)
is used to access the data using pointer
variable.
A pointer pointing to a struct is called
Structure pointer
main( )
{
struct book
{
char name[25] ;
char author[25] ;
int callno ;
};
struct book b1 = { "C Programming", "Robert Lafore", 101 } ;
struct book *ptr ;
ptr = &b1 ;
printf ( "\n%s %s %d", b1.name, b1.author, b1.callno ) ;
printf ( "\n%s %s %d", ptr->name, ptr->author, ptr->callno ) ;
printf("\n name is %s",(*ptr).name );}
(*ptr_dog).name - refers to the name of dog
(*ptr_dog).breed - refers to the breed of dog
Structure using Pointer (Example)
#include <stdio.h> int main()
#include <string.h> {
struct student record1 = {1, "Raju", 90.5};
struct student struct student *ptr;
{
int id; ptr = &record1;
char name[30];
float percentage; printf("Records of STUDENT1: \n");
}; printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->
percentage);

return 0;
}
the typedef keyword to allow users to provide alternative names for
the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types.

#include<stdio.h> #include<stdio.h>

struct Point{ typedef struct Point{


int x; int x;
int y; int y;
}; } Point;
typedef struct Point Point; int main() {
int main() { Point p1;
Point p1; p1.x = 1;
p1.x = 1; p1.y = 3;
p1.y = 3; printf("%d \n", p1.x);
printf("%d \n", p1.x); printf("%d \n", p1.y);
printf("%d \n", p1.y); return 0;
return 0; }
}
UNION
• A union is a special data type available in C that
allows to store different data types in the same
memory location.
• You can define a union with many members, but only
one member can contain a value at any given time.
• Unions provide an efficient way of using the same
memory location for multiple-purpose.
• The union variable allocates the memory space equal
to the space to hold the largest variable of union.
Defining a Union
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
Features of Union

• Similar to structures

• Can have array

• Can be nested inside structures

• Structures can be nested within union

• nesting structure in union is also possible.


Advantages of union

• Here, are pros/benefits for using union:


• It occupies less memory compared to structure.
• When you use union, only the last variable can be
directly accessed.
• Union is used when you have to use the same
memory location for two or more data members.
• It enables you to hold data of only one data
member.
• Its allocated space is equal to maximum size of
the data member.
Creating Union variables
union car union car
{ {
char name[50]; char name[50];
int price; OR int price;
} car1, car2, *car3; };

int main()
{
union car car1, car2, *car3;
return 0;
}
Accessing members of a union
• To access price for union variable car1
car1.price

• To access price for the union pointer variable car3


(*car3).price
or
car3->price
Difference between structure and union in context of programming
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Difference between union and structure
There is a difference in memory allocation between union
and structure.
STRUCTURE UNION

• The amount of memory • The memory required to


required to store a structure store a union variable is the
variable is the sum of memory required for the
memory size of all largest element of an union.
members.
Accessing Union Members (Example1)
#include <stdio.h>
#include <string.h>

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

int main( ) { OUTPUT

union Data data;


data.i : 1917853763
data.i = 10; data.f : 4122360580327794860452759994368.000000
data.f = 220.5; data.str : C Programming
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;
}
Accessing Union Members (Example 2)
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20]; OUTPUT
};
data.i : 10
int main( ) data.f : 220.500000
{ 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;
}
scanf("%f", &set.st.percentage);
#include<stdio.h>
printf("\nThe student details are : \n");
#include<stdlib.h>
printf("\name : %s", set.st.name);
printf("\nRollno : %d", set.st.rollno);
void main()
printf("\nSex : %c", set.st.sex);
{
printf("\nPercentage : %f", set.st.percentage);
struct student {
}
char name[30];
char sex;
int rollno;
float percentage;
};
union details {
struct student st;
};
union details set;
printf("Enter details:");
printf("\nEnter name : ");
scanf("%s", set.st.name);
printf("\nEnter roll no : ");
scanf("%d", &set.st.rollno);
printf("\nEnter sex : ");
fflush(stdin);
scanf("%c", &set.st.sex);
printf("\nEnter percentage :");

You might also like