SlideShare a Scribd company logo
1 of 16
Structure
Sometime, it may require to process multiple data stucture whose individual data elements can
be differ in type. In a single structure may contain integer element, floating point element and
character element. It may consist of arrays, pointers and other structures as element of the
structure.
So, a combination of data structure with various type of elements within the same storage class, is
known as structure in C.
Defining a structure
It is a little bit difficult to define a structure with comparing to an array. Since in a structure, it
may consist of various data elements and each data element is to be defined separately within the
structure such as:
struct tag {
member 1;
member 2;
member 3;
…………..
………….
member m;
};
where struct is a keyword which defines the following combination is a structure.
tag represents the name of structure of combined members included within compound statement.
and, member 1,member 2, member 3,……..member m are the individual declaration of elements
of current structure.
• The individual member can be ordinary variable, array, pointer or other structure.
• The name must be distinct from another structure.
• But the member name of the structure and outside the structure may be same but refers to
different identity.
• Storage class can not be defined for individual members and also cannot be initialized
individual members within the structure.
Once the composition of structure has been defined, individual structure type variables can be
declared as follows:
storage_class struct tag variable 1, variable 2, variable 3, ……., variable n;
where, storage class is optional.
struct is required keyword to declare following variables as structures.
tag is the name of the structure
and variable 1, variable 2, variable 3 are the structure variables.
e.g.
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
};
1
struct account oldcustomer, newcustomer;
It is also possible to combine the declaration of structure with structure variables as follows:
storage_class struct tag {
member 1;
member 2;
member 3;
…………..
………….
member m;
}variable 1, variable 2, variable 3, ……., variable n;
Note : tag is optional in this case.
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
} oldcustomer, newcustomer;
A structure may also consist of another structure as a member of structure but the embedded
structure must be declared before the outer structure.
eg.
struct date {
int month;
int day;
int year;
};
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
} oldcustomer, newcustomer;
The member of a structure can not be initialized within the structure. It can be initialized in the
same order as they are defined within the structure as follows:
storage_class struct tag variable={value 1, value 2, value 3......., value m};
e.g.
struct date {
int month;
int day;
int year;
};
2
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
};
static struct account customer = {101,’S’, “Anup”, 10000.50, 5, 15, 04};
array of structure
It can also be defined an array of structures upon which each element of the array represents a
structure.
e.g.
struct date {
int month;
int day;
int year;
};
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
}customer[100];
In this declaration, each element of array represents a structure of a customer. So, we have 100
structures for 100 customers. That means, we can store 100 records of customer in this data
structure.
Processing a structure
The members of a structure are usually processed individually, as separate entities. So, each
member of a structure can be accessed individually as follows:
variable.member
where variable refers to name of a structure type variable
and, member refers to name of a member of the structure.
e.g.
customer.acctno
where, customer refers to name of structure
and accno refer to member of the structure
similarly,
3
customer.name
customer.balance
etc.....
let’s see some expressions
++customer.balance
customer.balance++
&customer.balance
Similarly, it can also be accessed sub-member of a structure as follows:
variable.member.submember
where variable refers to name of a structure type variable
member refers to name of a member within outer structure
and, submember refers to name of the member within the embedded structure.
e.g.
customer.lastpayment.month
/* to read input of a customer and write out it’s information again */
#include<stdio.h>
struct date {
int month;
int day;
int year;
};
struct account {
int acctno;
char acct_type;
char name[80];
int balance;
struct date lastpayment;
}customer[100];
main()
{
int i,n;
printf(“n How many no. of cusstomer?”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
readinput();
for(i=0;i<n;i++)
writeoutput();
}
4
void writeoutput(int i)
{
printf(“n Customer No.: %d”,i+1);
printf(“Name : %s”,customer[i].name );
printf(“Account Number : %d “,customer[i].acctno );
printf(“Account Type : %c “,customer[i].acct_type );
printf(“Balance : %d “,customer[i].balance );
printf(“Payment Date : %d/%d/%d “,customer[i].lastpayment.month,
customer[i].lastpayment.day, customer[i].lastpayment.year);
}
void readinput(int i)
{
printf(“n Customer No.: %d”,i+1);
printf(“Name : “);
scanf(“%[^n] “,customer[i].name );
printf(“Account Number : “);
scanf(“%d “,&customer[i].acctno );
printf(“Account Type : “);
scanf(“%c “,&customer[i].acct_type );
printf(“Balance : “);
scanf(“%d “,&customer[i].balance );
printf(“Payment Date : “);
scanf(“%d/%d/%d“,&customer[i].lastpayment.month, &customer.lastpayment.day,
&customer.lastpayment.year);
}
User Defined data types(typedef)
In c, the data type of any identity can be customized by the user. i.e. new data type can also be
made so that such type can be used to define any identities. typedef is the keyword, which enables
users to define new data type equivalent to existing data types. Such user defined data types can
be used any new variables, arrays, structures. New data type can be defined as follows:
typedef type new_type;
e.g.
typedef int age;
age male female;
and, is equivalent to
int male, female;
Similarly,
typedef float cust[100];
cust newcust,oldcust;
or,
typedef float cust;
cust newcust[100],oldcust[100];
By the same way, it can also be used to define a structure too. It removes the repeatition of struct
tag.
In general,
5
typdef struct{
member 1;
member 2;
...............
member m;
}new_type;
e.g.
typedef struct{
int acctno;
char acct_type;
name[80];
float balance;
}record;
record oldcustomer,newcustomer;
Here, record is defined as new structure data type and newly define data type is used to define
structure variables oldcustomer and newcustomer.
Different ways of declaration of structures
typedef struct {
int month;
int day;
int year;
}date;
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}record;
record customer[100];
typedef struct {
int month;
int day;
int year;
}date;
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}record[100];
record customer;
typedef struct {
int month;
int day;
int year;
}date;
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}customer[100];
Structures and Pointers
The beginning address of a structure can also be accessed in the same manner as other address,
using &(address) operator. So, a variable represents a structure, it can also be represented its
address as &variable and pointer to the structure can be denoted as *variable.
such as
type *ptvar;
A pointer to a structure can be defined as follows:
6
e.g.
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}account;
account customer, *pc=&customer;
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
} customer, *pc=&customer;
Here, customer is a structure variable of type account and pc is a pointer variable whose object is account type
structure. The beginning address of the structure can be accessed as
pc=&customer;
Generally, each member of structure can be accessed by using selection operator as
ptvar -> member
which is equivalent to
variable.member
The -> operator can be combined to period (.) operator and their associativity is left to right. Similarly, it can be used
for array too.
ptvar ->member[expn]
typedef struct {
int month;
int day;
int year;
}date;
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
} customer, *pc=&customer;
So, if we want to access customer’s account number, then we can write any one of these
customer.acctno pc->acctno (*pc).acct_no
Similary, for month of last payment,
customer.lastpayment.month
pc->lastpayment.month
(*pc).lastpayment.month
If the structure is defined as:
struct {
int *acctno;
char *acct_type;
char *name;
7
float *balance;
date lastpayment;
} customer, *pc=&customer;
So, if we want to access customer’s account number, then we can write any one of these
*customer.acctno *pc->acctno *(*pc).acct_no
struct2.cpp
/* To access data items from members of structure */
#include<stdio.h>
#include<conio.h>
void main()
{
int n=111;
char t='c';
float b=99.99;
char name[20]="srijan";
int d=25;
typedef struct {
int *month;
int *day;
int *year;
}date;
struct {
int *acctno;
char *acct_type;
char *name;
float *balance;
date lastpayment;
}customer,*pc=&customer;
pc->acctno=&n;
customer.acct_type=&t;
customer.name=name;
customer.balance=&b;
*customer.lastpayment.day=25;
clrscr();
printf("n%d %c %s %.2f %d", *customer.acctno, *customer.acct_type, customer.name,
*customer.balance, *customer.lastpayment.day);
printf("n%d %c %s %.2f %d",*(*pc).acctno,*pc->acct_type,
pc->name,*pc->balance,*pc->lastpayment.day);
8
getch();
}
struct3.cpp
/* To determine the size of a structure and it's address */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
typedef struct {
int month;
int day;
int year;
}date;
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}customer, *pc=&customer;
printf("nNumber of bytes %d",sizeof *pc);
printf("nstarting address : %d",pc);
printf("nstarting address : %d",++pc);
getch();
}
Passing structure to a function
A structure can generally be passed to a function by two ways. Either, individual members can be passed to a function
or entire structure can be passed to a function. By the same way a single member can be returned back to the function
reference or entire structure.
In general,
void main()
{
typedef struct {
int month;
int day;
int year;
}date;
9
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}customer;
float modify(char name[], int acctno, float balance);
....................
customer.balance = modify(name, acctno, balance);
....................
}
float modify(char name[], int acctno, float balance)
{
float newbalance;
....................
newbalance = .........;
return(newbalance);
}
In this example, individual member is passed to a function and the new value is returned back to a member of a
structure.
struct4.cpp
/* To pass an entire structure to a function*/
#include<stdio.h>
#include<conio.h>
typedef struct {
int acctno;
char acct_type;
char *name;
float balance;
}record;
void main()
{
void modify(record *pc);
record customer={101,'c',"Anup",5000.00};
printf("n%d %c %s %.2f",customer.acctno,customer.acct_type,customer.name,customer.balance);
modify(&customer);
printf("nn%d %c %s %.2f", customer.acctno, customer.acct_type, customer.name, customer.balance);
10
getch();
}
void modify(record *pc)
{
pc->acctno=999;
pc->acct_type='d';
pc->name="Sabin";
pc->balance=99999.99;
}
In this example, it passes entire structure to the function with it's address, then modifies values of member
of the structure and finally returns back to the function reference with modified values of the structure.
struct5.cpp
/*to illustrate how an array of structure is passed to a function, and how a
pointer to a particular structure is returned */
#include<stdio.h>
#include<conio.h>
#define N 3
typedef struct {
int acctno;
char acct_type;
char *name;
float balance;
}record;
void main()
{
static record customer[N]={
{101,'c',"Anup",5000.00},
{102,'d',"Anil",9000.00},
{103,'o',"Sabina",7000.00}
};
int ano;
record *pc;
record *search(record table[N], int ano);
do{
printf("n Enter the record no. to be searched, type 0 to end");
scanf("%d",&ano);
pc=search(customer,ano);
if(pc!=0)
{
printf("n Name : %s",pc->name);
printf("n Account No. : %d",pc->acctno);
11
printf("n Account type : %c",pc->acct_type);
printf("n Balance : %.2f",pc->balance);
}
else
printf("n Error - Record not found");
} while(ano!=0)
}
record *search(record table[N], int ano)
{
int i;
for(i=0;i<N;i++)
if(table[i].acctno==ano)
return(&table[i]);
return(0);
}
Unions
It is similar to a structure which may contain individual data item may be different data types of same storage class.
Each member of the structure is assigned its own unique storage area in memory whereas all members of a union share
the same storage area in memory. It reserves the space equivalent to that of member which requires highest memory.
So, it is used to conserve memory. It is useful to such applications, where all members need not to be assigned value at
the same time. If assigned, it will produce meaningless result.
In general,
union tag {
member 1;
member 2;
...............
member m;
};
storage-class union tag variable1, variable2, ..........variable n;
or, combined form,
storage-class union tag {
member 1;
member 2;
...............
member m;
}variable1, variable2, ..........variable n;
e.g.
union id{
char color[12];
int size;
}shirt, blouse;
12
Here we've two union variables, shirt and blouse of type id and occupies 12 bytes in memory, however value is
assigned to any union variable.
e.g.
union id{
char color[12];
int size;
};
struct clothes{
char manufacturer[20];
float cost;
union id description;
}shirt, blouse;
Here, shirt and blouse are structure clothes type variables. Each variable contains manufacturer, cost and either
of color or size.
Each individual member can be accessed in the same way as structure using . and -> operators.
struct6.cpp
/* a program using union */
# include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
union id{
char color[12];
int size;
};
struct clothes{
char manufacturer[20];
float cost;
union id description;
}shirt, blouse;
printf("%d",sizeof(union id));
scanf("%s",shirt.description.color);
printf("n %s %d ", shirt.description.color, shirt.description.size);
shirt.description.size=12;
printf("n %s %d ", shirt.description.color, shirt.description.size);
getch();
}
struct7.cpp
13
#include<stdio.h>
#include<conio.h>
#include<math.h>
typedef union {
float fexp; // floating point exponent
int nexp; // integer exponent
}nvals;
typedef struct{
float x;
char flag;
nvals exp;
}values;
void main()
{
values a;
float power(values a);
int i;
float n,y;
printf("y=x^nn enter value of x:");
scanf("%f",&a.x);
printf("enter value for n: ");
scanf("%f",&n);
i=(int) n;
a.flag=(i==n) ?'i' : 'f';
if(a.flag == 'i')
a.exp.nexp = i;
else
a.exp.fexp=n;
if(a.flag=='f' && a.x<=0.0)
{
printf("ERROR cannot raise negative no. to a");
printf("floating point power");
}
else
{
y=power(a);
printf("n y=%.4f",y);
}
getch();
}
float power(values a)
{
int i;
float y=a.x;
14
if(a.flag=='i')
{
if(a.exp.nexp==0)
y=1.0;
else
{
for(i=1;i<abs(a.exp.nexp);i++)
{
y*=a.x;
if(a.exp.nexp<0)
y=1.0/y;
}
}
}
else
y=exp(a.exp.fexp*log(a.x)); //y=exp(n(log(x)))
return(y);
}
What is a structure? How does a structure differ from an array?
What is member? Write down the relation between member and structure?
What is the purpose of the typedef feature? How is this feature used in conjuction with structures?
What is a union? How does a union differ from a structure?
15
Self Referential Structures
It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type.
Generally,
struct tag {
member 1;
member 2;
...........
struct tag *name;
};
where name refers to the name of a pointer variable. Thus the structure of type tag will have a member that
points to another structure of type tag. Such structure is known as Self-referential structure.
eg.
struct list{
char item[40];
struct list *name;
};
16

More Related Content

Similar to 9.structure & union

Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9patcha535
 
Ch7 structures
Ch7 structuresCh7 structures
Ch7 structuresHattori Sidek
 
Str
StrStr
StrAcad
 
Structures in c++
Structures in c++Structures in c++
Structures in c++Swarup Boro
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.pptParinayWadhwa
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and TypedefAcad
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And UnionsDhrumil Patel
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and UnionsDhrumil Patel
 
Definition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptxDefinition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptxAnithaTAssistantProf
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structuresKrishna Nanda
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptxMehul Desai
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structureshaibal sharif
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languagetanmaymodi4
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languageTanmay Modi
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RERajeshkumar Reddy
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing conceptskavitham66441
 

Similar to 9.structure & union (20)

Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 
Ch7 structures
Ch7 structuresCh7 structures
Ch7 structures
 
Str
StrStr
Str
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and Typedef
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Definition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptxDefinition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptx
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Programming in C
Programming in CProgramming in C
Programming in C
 

More from Shankar Gangaju

More from Shankar Gangaju (20)

Tutorial no. 8
Tutorial no. 8Tutorial no. 8
Tutorial no. 8
 
Tutorial no. 7
Tutorial no. 7Tutorial no. 7
Tutorial no. 7
 
Tutorial no. 6
Tutorial no. 6Tutorial no. 6
Tutorial no. 6
 
Tutorial no. 3(1)
Tutorial no. 3(1)Tutorial no. 3(1)
Tutorial no. 3(1)
 
Tutorial no. 5
Tutorial no. 5Tutorial no. 5
Tutorial no. 5
 
Tutorial no. 4
Tutorial no. 4Tutorial no. 4
Tutorial no. 4
 
Tutorial no. 2
Tutorial no. 2Tutorial no. 2
Tutorial no. 2
 
Tutorial no. 1.doc
Tutorial no. 1.docTutorial no. 1.doc
Tutorial no. 1.doc
 
What is a computer
What is a computerWhat is a computer
What is a computer
 
Pointer
PointerPointer
Pointer
 
Array
ArrayArray
Array
 
6.array
6.array6.array
6.array
 
5.program structure
5.program structure5.program structure
5.program structure
 
4. function
4. function4. function
4. function
 
3. control statement
3. control statement3. control statement
3. control statement
 
2. operator
2. operator2. operator
2. operator
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
Ads lab
Ads labAds lab
Ads lab
 
Electromagnetic formula
Electromagnetic formulaElectromagnetic formula
Electromagnetic formula
 
Electromagnetic formula
Electromagnetic formulaElectromagnetic formula
Electromagnetic formula
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 

9.structure & union

  • 1. Structure Sometime, it may require to process multiple data stucture whose individual data elements can be differ in type. In a single structure may contain integer element, floating point element and character element. It may consist of arrays, pointers and other structures as element of the structure. So, a combination of data structure with various type of elements within the same storage class, is known as structure in C. Defining a structure It is a little bit difficult to define a structure with comparing to an array. Since in a structure, it may consist of various data elements and each data element is to be defined separately within the structure such as: struct tag { member 1; member 2; member 3; ………….. …………. member m; }; where struct is a keyword which defines the following combination is a structure. tag represents the name of structure of combined members included within compound statement. and, member 1,member 2, member 3,……..member m are the individual declaration of elements of current structure. • The individual member can be ordinary variable, array, pointer or other structure. • The name must be distinct from another structure. • But the member name of the structure and outside the structure may be same but refers to different identity. • Storage class can not be defined for individual members and also cannot be initialized individual members within the structure. Once the composition of structure has been defined, individual structure type variables can be declared as follows: storage_class struct tag variable 1, variable 2, variable 3, ……., variable n; where, storage class is optional. struct is required keyword to declare following variables as structures. tag is the name of the structure and variable 1, variable 2, variable 3 are the structure variables. e.g. struct account { int acctno; char acct_type; char name[80]; float balance; }; 1
  • 2. struct account oldcustomer, newcustomer; It is also possible to combine the declaration of structure with structure variables as follows: storage_class struct tag { member 1; member 2; member 3; ………….. …………. member m; }variable 1, variable 2, variable 3, ……., variable n; Note : tag is optional in this case. struct account { int acctno; char acct_type; char name[80]; float balance; } oldcustomer, newcustomer; A structure may also consist of another structure as a member of structure but the embedded structure must be declared before the outer structure. eg. struct date { int month; int day; int year; }; struct account { int acctno; char acct_type; char name[80]; float balance; struct date lastpayment; } oldcustomer, newcustomer; The member of a structure can not be initialized within the structure. It can be initialized in the same order as they are defined within the structure as follows: storage_class struct tag variable={value 1, value 2, value 3......., value m}; e.g. struct date { int month; int day; int year; }; 2
  • 3. struct account { int acctno; char acct_type; char name[80]; float balance; struct date lastpayment; }; static struct account customer = {101,’S’, “Anup”, 10000.50, 5, 15, 04}; array of structure It can also be defined an array of structures upon which each element of the array represents a structure. e.g. struct date { int month; int day; int year; }; struct account { int acctno; char acct_type; char name[80]; float balance; struct date lastpayment; }customer[100]; In this declaration, each element of array represents a structure of a customer. So, we have 100 structures for 100 customers. That means, we can store 100 records of customer in this data structure. Processing a structure The members of a structure are usually processed individually, as separate entities. So, each member of a structure can be accessed individually as follows: variable.member where variable refers to name of a structure type variable and, member refers to name of a member of the structure. e.g. customer.acctno where, customer refers to name of structure and accno refer to member of the structure similarly, 3
  • 4. customer.name customer.balance etc..... let’s see some expressions ++customer.balance customer.balance++ &customer.balance Similarly, it can also be accessed sub-member of a structure as follows: variable.member.submember where variable refers to name of a structure type variable member refers to name of a member within outer structure and, submember refers to name of the member within the embedded structure. e.g. customer.lastpayment.month /* to read input of a customer and write out it’s information again */ #include<stdio.h> struct date { int month; int day; int year; }; struct account { int acctno; char acct_type; char name[80]; int balance; struct date lastpayment; }customer[100]; main() { int i,n; printf(“n How many no. of cusstomer?”); scanf(“%d”,&n); for(i=0;i<n;i++) readinput(); for(i=0;i<n;i++) writeoutput(); } 4
  • 5. void writeoutput(int i) { printf(“n Customer No.: %d”,i+1); printf(“Name : %s”,customer[i].name ); printf(“Account Number : %d “,customer[i].acctno ); printf(“Account Type : %c “,customer[i].acct_type ); printf(“Balance : %d “,customer[i].balance ); printf(“Payment Date : %d/%d/%d “,customer[i].lastpayment.month, customer[i].lastpayment.day, customer[i].lastpayment.year); } void readinput(int i) { printf(“n Customer No.: %d”,i+1); printf(“Name : “); scanf(“%[^n] “,customer[i].name ); printf(“Account Number : “); scanf(“%d “,&customer[i].acctno ); printf(“Account Type : “); scanf(“%c “,&customer[i].acct_type ); printf(“Balance : “); scanf(“%d “,&customer[i].balance ); printf(“Payment Date : “); scanf(“%d/%d/%d“,&customer[i].lastpayment.month, &customer.lastpayment.day, &customer.lastpayment.year); } User Defined data types(typedef) In c, the data type of any identity can be customized by the user. i.e. new data type can also be made so that such type can be used to define any identities. typedef is the keyword, which enables users to define new data type equivalent to existing data types. Such user defined data types can be used any new variables, arrays, structures. New data type can be defined as follows: typedef type new_type; e.g. typedef int age; age male female; and, is equivalent to int male, female; Similarly, typedef float cust[100]; cust newcust,oldcust; or, typedef float cust; cust newcust[100],oldcust[100]; By the same way, it can also be used to define a structure too. It removes the repeatition of struct tag. In general, 5
  • 6. typdef struct{ member 1; member 2; ............... member m; }new_type; e.g. typedef struct{ int acctno; char acct_type; name[80]; float balance; }record; record oldcustomer,newcustomer; Here, record is defined as new structure data type and newly define data type is used to define structure variables oldcustomer and newcustomer. Different ways of declaration of structures typedef struct { int month; int day; int year; }date; typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }record; record customer[100]; typedef struct { int month; int day; int year; }date; typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }record[100]; record customer; typedef struct { int month; int day; int year; }date; struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }customer[100]; Structures and Pointers The beginning address of a structure can also be accessed in the same manner as other address, using &(address) operator. So, a variable represents a structure, it can also be represented its address as &variable and pointer to the structure can be denoted as *variable. such as type *ptvar; A pointer to a structure can be defined as follows: 6
  • 7. e.g. typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }account; account customer, *pc=&customer; typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; } customer, *pc=&customer; Here, customer is a structure variable of type account and pc is a pointer variable whose object is account type structure. The beginning address of the structure can be accessed as pc=&customer; Generally, each member of structure can be accessed by using selection operator as ptvar -> member which is equivalent to variable.member The -> operator can be combined to period (.) operator and their associativity is left to right. Similarly, it can be used for array too. ptvar ->member[expn] typedef struct { int month; int day; int year; }date; struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; } customer, *pc=&customer; So, if we want to access customer’s account number, then we can write any one of these customer.acctno pc->acctno (*pc).acct_no Similary, for month of last payment, customer.lastpayment.month pc->lastpayment.month (*pc).lastpayment.month If the structure is defined as: struct { int *acctno; char *acct_type; char *name; 7
  • 8. float *balance; date lastpayment; } customer, *pc=&customer; So, if we want to access customer’s account number, then we can write any one of these *customer.acctno *pc->acctno *(*pc).acct_no struct2.cpp /* To access data items from members of structure */ #include<stdio.h> #include<conio.h> void main() { int n=111; char t='c'; float b=99.99; char name[20]="srijan"; int d=25; typedef struct { int *month; int *day; int *year; }date; struct { int *acctno; char *acct_type; char *name; float *balance; date lastpayment; }customer,*pc=&customer; pc->acctno=&n; customer.acct_type=&t; customer.name=name; customer.balance=&b; *customer.lastpayment.day=25; clrscr(); printf("n%d %c %s %.2f %d", *customer.acctno, *customer.acct_type, customer.name, *customer.balance, *customer.lastpayment.day); printf("n%d %c %s %.2f %d",*(*pc).acctno,*pc->acct_type, pc->name,*pc->balance,*pc->lastpayment.day); 8
  • 9. getch(); } struct3.cpp /* To determine the size of a structure and it's address */ #include<stdio.h> #include<conio.h> void main() { clrscr(); typedef struct { int month; int day; int year; }date; struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }customer, *pc=&customer; printf("nNumber of bytes %d",sizeof *pc); printf("nstarting address : %d",pc); printf("nstarting address : %d",++pc); getch(); } Passing structure to a function A structure can generally be passed to a function by two ways. Either, individual members can be passed to a function or entire structure can be passed to a function. By the same way a single member can be returned back to the function reference or entire structure. In general, void main() { typedef struct { int month; int day; int year; }date; 9
  • 10. struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }customer; float modify(char name[], int acctno, float balance); .................... customer.balance = modify(name, acctno, balance); .................... } float modify(char name[], int acctno, float balance) { float newbalance; .................... newbalance = .........; return(newbalance); } In this example, individual member is passed to a function and the new value is returned back to a member of a structure. struct4.cpp /* To pass an entire structure to a function*/ #include<stdio.h> #include<conio.h> typedef struct { int acctno; char acct_type; char *name; float balance; }record; void main() { void modify(record *pc); record customer={101,'c',"Anup",5000.00}; printf("n%d %c %s %.2f",customer.acctno,customer.acct_type,customer.name,customer.balance); modify(&customer); printf("nn%d %c %s %.2f", customer.acctno, customer.acct_type, customer.name, customer.balance); 10
  • 11. getch(); } void modify(record *pc) { pc->acctno=999; pc->acct_type='d'; pc->name="Sabin"; pc->balance=99999.99; } In this example, it passes entire structure to the function with it's address, then modifies values of member of the structure and finally returns back to the function reference with modified values of the structure. struct5.cpp /*to illustrate how an array of structure is passed to a function, and how a pointer to a particular structure is returned */ #include<stdio.h> #include<conio.h> #define N 3 typedef struct { int acctno; char acct_type; char *name; float balance; }record; void main() { static record customer[N]={ {101,'c',"Anup",5000.00}, {102,'d',"Anil",9000.00}, {103,'o',"Sabina",7000.00} }; int ano; record *pc; record *search(record table[N], int ano); do{ printf("n Enter the record no. to be searched, type 0 to end"); scanf("%d",&ano); pc=search(customer,ano); if(pc!=0) { printf("n Name : %s",pc->name); printf("n Account No. : %d",pc->acctno); 11
  • 12. printf("n Account type : %c",pc->acct_type); printf("n Balance : %.2f",pc->balance); } else printf("n Error - Record not found"); } while(ano!=0) } record *search(record table[N], int ano) { int i; for(i=0;i<N;i++) if(table[i].acctno==ano) return(&table[i]); return(0); } Unions It is similar to a structure which may contain individual data item may be different data types of same storage class. Each member of the structure is assigned its own unique storage area in memory whereas all members of a union share the same storage area in memory. It reserves the space equivalent to that of member which requires highest memory. So, it is used to conserve memory. It is useful to such applications, where all members need not to be assigned value at the same time. If assigned, it will produce meaningless result. In general, union tag { member 1; member 2; ............... member m; }; storage-class union tag variable1, variable2, ..........variable n; or, combined form, storage-class union tag { member 1; member 2; ............... member m; }variable1, variable2, ..........variable n; e.g. union id{ char color[12]; int size; }shirt, blouse; 12
  • 13. Here we've two union variables, shirt and blouse of type id and occupies 12 bytes in memory, however value is assigned to any union variable. e.g. union id{ char color[12]; int size; }; struct clothes{ char manufacturer[20]; float cost; union id description; }shirt, blouse; Here, shirt and blouse are structure clothes type variables. Each variable contains manufacturer, cost and either of color or size. Each individual member can be accessed in the same way as structure using . and -> operators. struct6.cpp /* a program using union */ # include <stdio.h> #include<conio.h> void main() { clrscr(); union id{ char color[12]; int size; }; struct clothes{ char manufacturer[20]; float cost; union id description; }shirt, blouse; printf("%d",sizeof(union id)); scanf("%s",shirt.description.color); printf("n %s %d ", shirt.description.color, shirt.description.size); shirt.description.size=12; printf("n %s %d ", shirt.description.color, shirt.description.size); getch(); } struct7.cpp 13
  • 14. #include<stdio.h> #include<conio.h> #include<math.h> typedef union { float fexp; // floating point exponent int nexp; // integer exponent }nvals; typedef struct{ float x; char flag; nvals exp; }values; void main() { values a; float power(values a); int i; float n,y; printf("y=x^nn enter value of x:"); scanf("%f",&a.x); printf("enter value for n: "); scanf("%f",&n); i=(int) n; a.flag=(i==n) ?'i' : 'f'; if(a.flag == 'i') a.exp.nexp = i; else a.exp.fexp=n; if(a.flag=='f' && a.x<=0.0) { printf("ERROR cannot raise negative no. to a"); printf("floating point power"); } else { y=power(a); printf("n y=%.4f",y); } getch(); } float power(values a) { int i; float y=a.x; 14
  • 15. if(a.flag=='i') { if(a.exp.nexp==0) y=1.0; else { for(i=1;i<abs(a.exp.nexp);i++) { y*=a.x; if(a.exp.nexp<0) y=1.0/y; } } } else y=exp(a.exp.fexp*log(a.x)); //y=exp(n(log(x))) return(y); } What is a structure? How does a structure differ from an array? What is member? Write down the relation between member and structure? What is the purpose of the typedef feature? How is this feature used in conjuction with structures? What is a union? How does a union differ from a structure? 15
  • 16. Self Referential Structures It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type. Generally, struct tag { member 1; member 2; ........... struct tag *name; }; where name refers to the name of a pointer variable. Thus the structure of type tag will have a member that points to another structure of type tag. Such structure is known as Self-referential structure. eg. struct list{ char item[40]; struct list *name; }; 16