Structures, Unions, and Typedefs
System Programming Concepts
The C Programming Language
Structures, Unions, and 1
Typedefs
Definition — Structure
• A collection of one or more variables,
typically of different types, grouped
together under a single name for convenient
handling
• Known as struct in C
Structures, Unions, and 2
Typedefs
Structures (struct)
• A struct is a derived data type composed of
members that are each fundamental or
derived data types.
• A single struct would store the data for one
object. An array of structs would store the
data for several objects.
Declaring Structures (struct)
A struct can be defined in several ways as illustrated in the following
examples:
Does Not Reserve Space Reserves Space
struct my_example
{
struct my_example
int label; {
char letter; int label;
char name[20]; char letter;
};
char name[20];
/* The name "my_example" is
called a structure tag */ } mystruct ;
struct
• Defines a new type
• I.e., a new kind of data type that compiler regards as
a unit
• E.g.,
struct motor {
float volts; //voltage of the motor
float amps; //amperage of the motor
int phases; //# of phases of the motor
float rpm; //rotational speed of motor
}; //struct motor
Structures, Unions, and 5
Typedefs
struct
• Defines a new type
• E.g., Note:– name of type is optional if
struct motor { you are just declaring a single
float volts; struct
float amps;
int phases;
float rpm;
}; //struct motor
Structures, Unions, and 6
Typedefs
struct
• Defines a new type
• E.g.,
struct motor {
float volts;
float amps; Members of the
struct
int phases;
float rpm;
}; //struct motor
A member of a struct is analogous
to a field of a class in Java
Structures, Unions, and 7
Typedefs
Declaring struct variables
struct motor p, q, r;
• Declares and sets aside storage for three variables –
p, q, and r – each of type struct motor
struct motor M[25];
• Declares a 25-element array of struct motor;
allocates 25 units of storage, each one big enough to
hold the data of one motor
struct motor *m;
• Declares a pointer to an object of type struct
motor
Structures, Unions, and 8
Typedefs
Accessing Members of a struct
• Let
struct motor p;
struct motor q[10];
• Then
p.volts — is the voltage Like Java!
p.amps — is the amperage
p.phases — is the number of phases
p.rpm — is the rotational speed
q[i].volts — is the voltage of the (i+1)th motor
q[i].rpm — is the speed of the (i+1)th motor
Structures, Unions, and 9
Typedefs
Accessing Members of a struct (continued)
• Let
struct motor *p;
• Then
(*p).volts — is the voltage of the motor pointed
to by p
(*p).phases — is the number of phases of the
motor pointed to by p
Structures, Unions, and 10
Typedefs
Accessing Members of a struct (continued)
• The (*p).member notation is a nuisance
• Clumsy to type; need to match ( )
• Too many keystrokes
• This construct is so widely used that a
special notation was invented, i.e.,
– p->member, where p is a pointer to the
structure
• Ubiquitous in C
Structures, Unions, and 11
Typedefs
Previous Example Becomes …
• Let
struct motor *p;
• Then
p -> volts — is the voltage of the motor pointed
to by p
p -> phases — is the number of phases of the
motor pointed to by p
Structures, Unions, and 12
Typedefs
Operations on struct
• Copy/assign
struct motor p, q;
p = q;
• Get address
struct motor p;
struct motor *s
s = &p;
• Access members
p.volts;
s -> amps;
Structures, Unions, and 13
Typedefs
Below table explains following concepts in C structure.
How to declare a C structure?
How to initialize a C structure?
How to access the members of a C structure?
Type Using normal variable Using pointer variabe
Syntax struct tag_name struct tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example struct student struct student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
Declaring structure variable struct student report; struct student *report, rep;
Initializing structure variable struct student report = {10, “Ozi”, struct student rep = {10, “Ozi”,
3.14}; 3.14};
report = &rep;
Accessing structure members report.mark report -> mark
report.name report -> name
report.average report -> average
Structures, Unions, and 14
Typedefs
Initialization of a struct
• Let struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
• Then
struct motor m = {208, 20, 3, 1800};
initializes the struct
Structures, Unions, and 15
Typedefs
Example program for C structure:
#include <stdio.h>
#include <string.h>
Another way of declaring C structure
struct student
struct student
{
{
int id;
int id;
char name[20];
char name[20];
float percentage;
float percentage;
} record;
};
int main() struct student record;
{
struct student record; //Initializing to null
Id is: 1
record.id=1; Name is: Ozi
strcpy(record.name, “Ozi"); Percentage is: 16.500000
record.percentage = 16.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
16
return 0;
}
Example program for array of structures
struct student // 3rd student's record
{ record[2].id=3;
int id; strcpy(record[2].name, "Bruca");
char name[30]; record[2].percentage = 12.5;
float percentage;
};
for(i=0; i<3; i++)
{
int main() printf(" Records of STUDENT : %d \n", i+1);
{ printf(" Id is: %d \n", record[i].id);
int i; printf(" Name is: %s \n", record[i].name);
struct student record[3]; printf(" Percentage is: %f\n\n",record[i].percentage);
}
// 1st student's record
record[0].id=1; Records of STUDENT : 1
strcpy(record[0].name, "Ozi"); Id is: 1
Name is: Ozi
record[0].percentage = 16.5; Percentage is: 16.500000
Records of STUDENT : 2
// 2nd student's record Id is: 2
Name is: George
record[1].id=2;
Percentage is: 16.500000
strcpy(record[1].name, "George"); Records of STUDENT : 3
record[1].percentage = 16.5; Id is: 3 17
Name is: Bruca
Percentage is: 12.500000
Example for declaring many structure variable
struct student
{
int id; // 1st student's record
char name[30]; record1.id=1;
float percentage; record1.name="Ozi";
}; record1.percentage =
strcpy(record1.name, "Ozi"); 16.5;
int main()
{ // 2nd student's
int i;
record
struct student record1 = {1, "Ozi", 16.5};
struct student record2 = {2, "Ferrel", 93.5}; record2.id=2;
record2.name=“Ferrel";
printf("Records of STUDENT1: \n"); record2.percentage =
printf(" Id is: %d \n", record1.id); 93.5;
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage); Records of STUDENT1:
Id is: 1
printf("Records of STUDENT2: \n"); Name is: Ozi
Percentage is: 16.500000
printf(" Id is: %d \n", record2.id);
Records of STUDENT2:
printf(" Name is: %s \n", record2.name); Id is: 2
printf(" Percentage is: %f \n\n", record2.percentage); Name is: Ferrel
Percentage is: 93.500000
return 0; 18
}
Example program for structure using pointer
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, “Ozi", 99.5};
struct student *ptr;
Records of STUDENT1:
ptr = &record1; Id is: 1
Name is: Ozi
printf("Records of STUDENT1: \n"); Percentage is: 99.500000
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
19
Example program for structure using pointer
int main()
struct student
record1 structure
{
{ int i; Id : 1
int id; struct student record1 = {1, "Ozi", 16.5}; Name : Ozi
char name[30]; struct student record2, *record3, *ptr1, record4; Percentage : 16.500000
float percentage;
}; printf("record1 structure \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",
record1.id, record1.name, record1.percentage);
Direct copy from record1
record2=record1; Id : 1
Name : Ozi
ptr1 = &record1; Percentage : 16.500000
memcpy(record3, ptr1, sizeof(record1)); copied from record1 using memcpy
Id : 1
record4.id=record1.id; Name : Ozi
strcpy(record4.name, record1.name); Percentage : 16.500000
record4.percentage = record1.percentage; Copied individual members from record1
Return 0; Id : 1
} Name : Ozi
Percentage : 16.500000
20
Passing struct to function
It can be done in below 3 ways.
struct student
{
int id;
char name[20];
float percentage;
};
Passing structure to a function by value
void func(struct student record);
Passing structure to a function by address(reference)
void func(struct student *record);
No need to pass a structure – Declare structure variable as global
struct student record; // Global declaration of structure
void structure_demo();
21
Passing structure to a function by value
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student );
int main()
{
struct student record;
record.id=1;
Id is: 1
strcpy(record.name, “ozi");
Name is: Ozi
record.percentage = 86.5;
Percentage is: 86.500000
func(record);
return 0;
}
void func(struct student rec)
{
printf(" Id is: %d \n", rec.id);
printf(" Name is: %s \n", rec.name);
printf(" Percentage is: %f \n", rec.percentage); 22
}
Passing structure to a function
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *);
int main()
{
struct student record;
Id is: 1
record.id=1; Name is: Ozi
strcpy(record.name, “ozi"); Percentage is: 86.500000
record.percentage = 86.5;
func(&record);
return 0;
}
void func(struct student *rec)
{
printf(" Id is: %d \n", rec->id);
printf(" Name is: %s \n", rec->name);
23
printf(" Percentage is: %f \n", rec->percentage);
}
struct student
{
declare a structure variable as global
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
Id is: 1
{
Name is: Ozi
record.id=1; Percentage is: 86.500000
strcpy(record.name, “Ozi");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage); 24
}
Nested Structure
struct student_college_detail Id is: 1
{ Name is: Ozi
int college_id; Percentage is: 90.500000
char college_name[50]; College Id is: 41000
}; College Name is: Kocaeli University
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
student_detail student_college_detail
int main()
{
struct student_detail stu_data = {1, “Ozi", 90.5, 41000, “Kocaeli University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id);
printf(" College Name is: %s \n", stu_data.clg_data.college_name);
25
return 0;
}
Typedef
• Definition:– a typedef is a way of
renaming a type
• E.g.,
typedef struct motor Motor;
Motor m, n;
Motor *p, r[25];
Motor function(const Motor m; …);
Structures, Unions, and 26
Typedefs
•Typedef is a keyword that is used to give a new symbolic name for the existing name
in a C program. This is same like defining alias for the commands.
•Consider the below structure.
struct student
{
int mark [2];
char name [10];
float average;
};
•Variable for the above structure can be declared in two ways.
1st way :
struct student record; /* for normal variable */
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;
•When we use “typedef” keyword before struct <tag_name> like above, after that we
can simply use type definition “status” in the C program to declare structure variable.
•Now, structure variable declaration will be, “status record”.
•This is equal to “struct student record”. Type definition for “struct27 student” is status. i.e.
status = “struct student”
typedef (continued)
• typedef may be used to rename any type
– Convenience in naming
– Clarifies purpose of the type
– Cleaner, more readable code
– Portability across platforms
• E.g.,
– typedef char *String;
• E.g.,
– typedef int size_t;
– typedef long int32;
– typedef long long int64;
Structures, Unions, and 28
Typedefs
Unions
C Union is also like structure, i.e. collection of different data types which are grouped
together. Each element in a union is called member.
•Union and structure in C are same in concepts, except allocating memory for their
members.
•Structure allocates storage space for all its members separately.
•Whereas, Union allocates one common storage space for all its members
•We can access only one member of union at a time. We can’t access all member
values at the same time in union. But, structure can access all member values at the
same time. This is because, Union allocates one common storage space for all its
members. Whereas Structure allocates storage space for all its members separately.
•Many union variables can be created in a program and memory will be allocated for
each union variable separately.
29
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
Union record1 values example
union student record1; Name :
union student record2;
Subject :
// assigning values to record1 union variable
strcpy(record1.name, "Raju"); Percentage : 86.500000
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
Union record2 values example
// assigning values to record2 union variable
printf("Union record2 values example\n"); Name : Mani
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
Subject : Physics
strcpy(record2.subject, "Physics"); Percentage : 99.500000
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50; 30
printf(" Percentage : %f \n", record2.percentage);
return 0;
Unions (continued)
• unions are used much less frequently than
structs — mostly
• in the inner details of operating system
• in device drivers
• in embedded systems where you have to access
registers defined by the hardware
Structures, Unions, and 31
Typedefs
Questions?
32
Question For Final Exam
Write a C program whose description and functionality is given below.
Note That:
• Define a structure called “PupilRec“ that will describe the following information:
fName and fMark.
• fName is a variable with a length of 50 characters in a char data type.
• fMark is an integer variable.
• In the main function, using “PupilRec“, declare and initialize an array named
“players” with 4 elements that includes these elements “Armstrong 99 Azur
64 Bates 33 Zarra 81”.
• Define a function called as “MakeOrdered” that sorts the array defined with the
structure in ascending order according to “fMark” and No returns any value.
• Display the elements of the sorted array structured with “PupilRec” in the
function “MakeOrdered”.
• You must use only FOR loop.
• The output must be like below:
33
Answer For Final Exam
struct PupilRec { char fName[50]; int fMark; };
void MakeOrdered(struct PupilRec []);
int main(int argc, char *argv[]) {
struct PupilRec players[4]={"Armstrong",99,"Azur",64,"Bates",33,"Zarra",81};
MakeOrdered(players);
return 0;
} strcpy(temp.fName,arr[i].fName);
temp.fMark=arr[i].fMark;
void MakeOrdered(struct PupilRec arr[])
{
int i,j; struct PupilRec temp;
for(i=0;i<4;i++) {
for(j=i+1;j<4;j++) {
if(arr[i].fMark>arr[j].fMark)
1 2 3 4 5 6 7 8 9 1 2 3
{ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; }
}
}
for(i=0;i<4;i++) { printf("%9s%3d",arr[i].fName,arr[i].fMark);printf("\n"); }
} 34
EXAMPLE
Write a C program that uses functions to perform the
following operations for two complex numbers:
1. Addition
2. Subtraction
3. Multiplication
4. Division
(Note: represent complex number using a structure.)
35
Defining
the Structure and the Function Prototype
struct datacomplex
{
float real, imag;
};
struct datacomplex addx(struct datacomplex, struct datacomplex);
struct datacomplex subx(struct datacomplex, struct datacomplex);
struct datacomplex mulx(struct datacomplex, struct datacomplex);
struct datacomplex divx(struct datacomplex, struct datacomplex);
36
Building the Main Program
int main(int argc, char *argv[]) {
struct datacomplex Z1,Z2,Z;
printf("Enter a complex number=");scanf("%f %f",&Z1.real,&Z1.imag);printf("\n");
printf("Enter a complex number=");scanf("%f %f",&Z2.real,&Z2.imag);
printf("\n\n Addition \n\n");
Z=addx(Z1,Z2);printf("Z1+Z2=%.2f+j%.2f",Z.real,Z.imag);
printf("\n\n Subtraction \n\n");
Z=subx(Z1,Z2);printf("Z1-Z2=%.2f-j%.2f",Z.real,Z.imag);
printf("\n\n Multiplication \n\n");
Z=mulx(Z1,Z2);printf("Z1XZ2=%.2fXj%.2f",Z.real,Z.imag);
printf("\n\n Division \n\n");
Z=divx(Z1,Z2);printf("Z1/Z2=%.2fXj%.2f",Z.real,Z.imag);
return 0;
37
}
Creating the Functions addx and subx
struct datacomplex addx(struct datacomplex p, struct datacomplex q)
{
struct datacomplex zx;
zx.real = (p.real + q.real);
zx.imag = (p.imag + q.imag);
return zx;
}
struct datacomplex subx(struct datacomplex p, struct datacomplex q)
{
struct datacomplex zx;
zx.real = (p.real - q.real);
zx.imag = (p.imag - q.imag);
return zx;
}
38
Creating the Function mulx and divx
struct datacomplex mulx(struct datacomplex p, struct datacomplex q)
{
struct datacomplex zx;
zx.real=(p.real * q.real) - (p.imag * q.imag);
zx.imag=(p.real * q.imag) + (p.imag * q.real);
return zx;
}
struct datacomplex divx(struct datacomplex p, struct datacomplex q)
{
struct datacomplex zx;
zx.real = ((p.real * q.real) + (p.imag * q.imag)) / ((q.real * q.real) + (q.imag * q.imag));
zx.imag = ((p.imag * q.real) - (p.real * q.imag)) / ((q.real * q.real) + (q.imag * q.imag));
return(zx);
}
39