0% found this document useful (0 votes)
14 views38 pages

Chapter Three - Structures 2015

Chapter Three discusses the concepts of structures and unions in C++. It explains how structures allow for the grouping of different data types under a single name, and how unions share the same memory space for their members. The chapter also covers initializing structures, arrays of structures, nesting structures, and using typedef to create user-defined data types.

Uploaded by

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

Chapter Three - Structures 2015

Chapter Three discusses the concepts of structures and unions in C++. It explains how structures allow for the grouping of different data types under a single name, and how unions share the same memory space for their members. The chapter also covers initializing structures, arrays of structures, nesting structures, and using typedef to create user-defined data types.

Uploaded by

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

Chapter Three

Structure and Union

1
Contents
• Defining and Referencing Structure Members

• Initializing Structure Members

• Array of Structures

• Nesting Structures

• Defining and Referencing Unions

• Defining User Defined Data Types using typedef


Structures

 With array, we can only declare one data type per array.
 For different data type, we need another array declaration.
 Structure overcomes this problem by declaring composite data types which
can consist different types.
 A structure type is a user-defined composite type.
 It is composed of fields or members which can be different types.

3
Cont’d

A structure is a collection of one or more variable types grouped together

that can be referred using a single name (group name) and a member

name.

 In C++, a struct is same as a class except that its members are public by

default.

 In order to use a structure, we must first declare a structure template.

 The variables in a structure are called elements or members. 4


Cont’d
You can refer to a structure as a single variable, and you also can initialize,
read and change the parts of a structure (the individual variables that make it
up).
The General Syntax of structures is:
Struct [structure tag]
{
Member definition;
Member definition; …
Member definition;
}[one or more structure variables];

5
Cont’d
Let us see an example Structure tag
struct Inventory
{
char description[15];
char part_no[6]; members of the structure
int quantity;
float cost;
}; // all structures end with semicolon
 Another example might be:
struct Student {
char ID[8];
char FName[15];
char LName[15];
char Sex;
int age;
float CGPA; };
6
Cont’d
The above “Student” structure is aimed to store student record with all the
relevant details.
After the definition of the structure, one can declare a structure variable using
the structure tag. If we need two variables to have the above structure
property then the declaration would be:
struct Inventory inv1,inv2; //or
struct Student Stud1,stud2,Stud3;
Structure tag is not a variable name. Unlike array names, which reference the
array as variables, a structure tag is simply a label for the structure‘s format.
The structure tag Inventory informs C++ that the tag called Inventory looks
like two character arrays followed by one integer and one float variables.
A structure tag is actually a newly defined data type that you, or the
programmer, defined.

7
Referencing/accessing members of a structure
 To refer to the members of a structure we need to use the dot operator (.)
 The General syntax to access members of a structure variable would be:
[Link]
 Where VarName is the varaibale name of the structure variable And Member is varaibale
name of the members of the structure
 Eg:
For the above student structure:
struct Student Stud; //declaring Stud to have the property of the Student
structure strcpy([Link],”Abebe”); //assigned Abebe as First Name
[Link]=3.21; //assignes 3.21 as CGPA value of Abebe
cout<< [Link]; //display the name
cout<< [Link]; // display the CGPA of Abebe

8
Example
// Declare a structure named "car"
struct car {
string brand;
string model;
int year;
};

int main() {
// Create a car structure and store it in //myCar1;
car myCar1;
[Link] = "BMW";
[Link] = "X5";
[Link] = 1999;

9
Example(cont…)
// Create another car structure and store it in //myCar2;
car myCar2;
[Link] = "Ford";
[Link] = "Mustang";
[Link] = 1969;
// Print the structure members
cout << [Link] << " " << [Link] << " " << [Link] << "\n";
cout << [Link] << " " << [Link] << " " << [Link] << "\n";

return 0;
}

10
Initializing Structure Data
 You can initialize members when you declare a structure, or you can initialize a structure
in the body of the program. Here is a complete program.
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purchased[9];
} cd1 = {"Red Moon Men","Sams and the Sneeds", 12, 11.95,"08/13/93"};
cout<<"\nhere is the info about cd1"<<endl;
cout<<[Link]<<endl;
cout<<[Link]<<endl;
cout<<cd1.num_songs<<endl;
cout<<[Link]<<endl;
cout<<cd1.date_purchased<<endl
….
11
Cont’d
• A better approach to initialize structures is to use the dot operator(.). the dot operator is
one way to initialize individual members of a structure variable in the body of your
program.
[Link]
• here is an example:
#include<iostream>
#include<string>
struct cd_collection{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purchased[9];
}cd1;//initialize members here
12
Cont’d
int main()
{
strcpy([Link],"Red Moon Men");
strcpy([Link],"Sams");
cd1.num_songs= 12;
[Link] = 11.95f;
strcpy(cd1.date_purchased,"22/12/02"); //print the data
cout<<"\nHere is the info"<<endl;
cout<<"Title : "<<[Link]<<endl;
cout<<"Artist : "<<[Link]<<endl;
cout<<"Songs : "<<cd1.num_songs<<endl;
cout<<"Price : "<<[Link]<<endl;
cout<<"Date purchased : "<<cd1.date_purchased;
return 0;} 13
Cont’d
#include <iostream>
using namespace std;
struct Point {
int x = 0; // It is Considered as Default Arguments and no Error is Raised
int y = 1;
}; Output
int main() x=0, y=1
{ x=0, y=20
struct Point p1;
// Accessing members of point p1
// No value is Initialized then the default value is considered. ie x=0 and y=1;
cout << "x = " << p1.x << ", y = " << p1.y<<endl;
// Initializing the value of y = 20;
p1.y = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
14
return 0;}
Arrays of Structures
• Arrays of structures are good for storing a complete employee file, inventory file, or any
other set of data that fits in the structure format.
• Consider the following structure declaration:
struct Company
{
int employees;
int registers;
double sales;
}store[1000];
• In one quick declaration, this code creates 1,000 store structures with the definition of
the Company structure, each one containing three members.
• NB. Be sure that your computer does not run out of memory when you create a large
number of structures. Arrays of structures quickly consume valuable information.
• You can also define the array of structures after the declaration of the structure. 15
Cont’d
struct Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet
#include<iostream>

void main()
{
struct Company store[1000]; //the variable store is array of the
structure Company

16
}
Referencing the array structure
• The dot operator (.) works the same way for structure array element as it does
for regular variables. If the number of employees for the fifth store (store[4])
increased by three, you could update the structure variable like this:

store[4].employees += 3;

• Unlike in the case of arrays, where the whole content of an array could not be
copied to another one using a simple statement, in structures, you can assign
complete structures to one another by using array notation.

• To assign all the members of the 20th store to the 45th store, you would do this:

store[44] = store[19];//copies all members from 20th store to 45th 17


Nesting Structures

• When a structure contains another structure, it is called nested


structure.

• For example, if we have two structures named Address and


Employee. To make Address nested to Employee, we have to define
Address structure before and outside Employee structure and create
an object of Address structure inside Employee structure.

18
Cont’d

struct address
{
--------------------
};
struct employee
{
- - - - - - - - - - - - - - - - - - - - struct address obj;
};

19
Example

struct addr // structure tag


{
int houseno ;
char area[26] ;
char city[26] ;
char state[26] ;
};
struct emp // structure tag
{
addr ad;
int empno ;
char name[26] ;
char desig[16] ;
float basic ;
}worker ; // create structure variable 20
C++ Accessing Nested Structure Member

 The members of structures are accessed using dot operator. To access


the city member of address structure which is an element of another
structure worker, we shall write :
[Link]
 To initialize houseno member of address structure, element of
worker structure, we can write as follows:
[Link] = 1693
 As you can see, the elements of each structure are referenced from
outermost to innermost.
21
union

• A derived data type, whose members share the same storage


space.
• The members of a union can be of any type and the number of
bytes used to store a union must be at least enough to hold the
largest member.
• Unions contain two or more data types. Only one member, and thus
one data type, can be referenced at a time.
• Unions are declared and used in the same way as structures. Like
structures, it is also used to store different types of data. 22
Defining a Union
• Let's look at the syntax of a union.

union union_name
{
data-type member-1;
data-type member-2;
data-type member-3;
data-type member-4;
};
This is the same as the syntax of structure, except for the difference that in
place of the keyword struct, we wrote the keyword union. 23
Cont’d

• Let's take the same example we took in structure. Here we will take the
name of union as student and name, roll_no and phone_number as its
members as follows.

union student
{
int roll_no;
string name;
int phone_number;
}; 24
Declaration of Union Variable

• We declare the variables of a union in the same way as we declare those of a

structure.

• Again, let's take the same example in which we stored the roll no, name

and phone number of three students. To do this, we will define a union

named student as we have defined above and then we will declare its three

variables p1, p2 and p3 (which will represent the three students

respectively) in the main function. 25


Cont’d

union student
{
int roll_no;
string name;
int phone_number;
};
int main()
{
union student p1, p2, p3;
return 0;
}

26
Cont’d

There is another method of declaring union variables where we declare


these at the time of defining the union as follows.

union student
{
int roll_no;
string name;
int phone_number;
}p1, p2, p3;

27
Cont’d

Like structure, we assign the name, roll no and phone number of the first

student (suppose p1) by accessing its name, roll_no and phone number as

follows.

p1.roll_no = 1;

[Link] = "Brown“

Till now, you must have found union similar to structure. Now let's look at

the differences between the two. 28


Difference between union and structure

Before going into the differences, let's first look at an example.

29
Cont’d

• Talking about the above example, the amount of memory required to


store a structure is the sum of the memory sizes of all its
members.

• In the above example, the memory sizes of the variables roll_no and
phone_number will be 4 bytes each (since both are of type integer) and the
memory size of the character array name[40] will be 40 bytes (since the
array occupies the memory of 40 characters and the size of char is 1).

• Thus the memory occupied by the structure will be 4+40+4 = 48 bytes.


30
Cont’d

• Now coming to the union, the memory size of a union is equal to


the size of its member occupying the maximum space in the
memory.

• The size of roll_no and phone_number is 4 bytes each and that of name[40]
is 40 bytes. So, the union will occupy a memory space of 40 byte

31
Cont’d

• We can access only one member of union at a time because we have only

one location in memory for it, so only one of the member can be used at a

time.

• All the other members will contain the garbage value (i.e. will get

corrupted). This is not the case with structures where we can access all the

member's variables at the same time because each occupies a different

memory space. 32
Cont’d

• Now let's see an example of union.

33
Cont’d

• As you can see, the name got printed as it is and garbage value got printed
as roll number and phone number. Let's see why this happened.
• We know that we can access only one member of union at a time and the
other members get corrupted. So, when we wrote p1.roll_no = 1,
member 'roll_no' got accessed and got assigned a value '1’.
• After that, by writing p1.phone_number = 1234567822, we assigned a
value to the member 'phone_number'. Finally, we assigned a string value
"Brown" to the member 'name' as strcpy([Link],"Brown") and now,
the other two members 'roll_no' and 'phone_number' contains a garbage
value.
• Thus, the value of name got printed as it is and the values of the other two
variables in the output are the garbage values of those two.

34
Cont’d

• Let's see one more example.

35
Defining User Defined Data Types using typedef
• Typedef : C++ allows you to define explicitly new data type names by
using the keyword typedef.

• Using typedef does not actually create a new data class, rather it defines a
name for an existing type.

• It is very difficult to write unsigned short int many times in your program
if many variables need such kind of declaration.

• C++ enables you to substitute an alias for such phrase by using the
keyword typedef, which stands for type definition.

36
Cont’d
#include<iostream.h>

typedef unsigned short int USHORT;

void main()

USHORT width = 9;

37
38

You might also like