Professional Documents
Culture Documents
NMK10603 - Chapter 7 - Struct
NMK10603 - Chapter 7 - Struct
STRUCTURES
Chapter 7
Outline
2
Introduction
Structure Definitions and Declarations
Initializing Structures
Operations on Structures Members
Structures as Functions Parameters
Array of Structures
What is Structures?
3
Syntax:
struct StructureName
{
structure member declaration list
};
Example:
struct book
{
float fPrice;
int iNumPages;
int iYear;
};
Structure Definition
5
struct information
A struct cannot contain an instance of itself
Can contain a member that is a pointer to the same
structure type
A structure definition does not reserve space in memory
• Instead creates a new data type used to define structure
variables
Structure Declaration
6
OR
sBook1.fPrice = 25.50;
sBook1.iNumPages = 690;
sBook1.iYear = 2005;
dot operator
Operations on Structures Members
9
Example:
struct book sMyBook, sHisBook, sHerBook;
Example:
struct book sMyBook, sHisBook, sHerBook;
sMyBook. fPrice = 25.50;
sHerBook.fPrice = 10.50;
if(sMyBook.fPrice > sHerBook.fPrice)
printf(“My book is more expensive than hers\n”);
else
printf(“My book is cheaper than hers\n”);
Multiple Structures Variables
(Example)
12
……
float fnComputePrice(struct book sBkC); //function prototype
…
int main( )
{ struct book sBookC;
……………
fNewPrice = fnComputePrice(sBookC); //function call
……
}
float fnComputePrice(struct book sBkC) //function definition
{ …….
sBkC.fPrice=sBkC.fPrice + fTax;
……
return(fBkC.fPrice);
}
Structures as Function Parameters
15
…..
return(sBk);
}
Structures as Function Parameters
16
int iCounter;
const arraySize = 5;
struct listType
{
int aiListElem[arraySize]; //array containing the list
int iListLength; //length of the list
}; aiListElem
iListLength
Structure Within a Structure
24
//variable declaration
struct employeeType sNewEmployee;
//declare 100 employees' records
struct employeeType asEmployees[100];
sNewEmployee.dSalary = 45678.00;
sNewEmployee.sName.acFirst = "Mary";
sNewEmployee.sName.acMiddle = "Beth";
sNewEmployee.sName.acLast = "Simmons";
//reads and stores a string into sNewEmployee.sName.acFirst
scanf(“%s”, &sNewEmployee.sName.acFirst);
//updates the salary of newEmployee
sNewEmployee.dSalary = sNewEmployee.dSalary * 1.05;
PGT 106: Computer Programming 26