Struct

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

7/31/2018

Structs in C++
Instructor: Ali AlSbou

Records (structs)

• Structure is a collection of variables under a


single name. Variables can be of any type:
int, float, char etc.
• The main difference between structure and
array is that arrays are collections of the
same data type and structure is a collection of
variables under a single name.

1
7/31/2018

Records (structs)

• Components of a struct are called the members (or


fields) of the struct
• struct is a reserved word
• Examples:
− Student record: student id, name, major, gender, start
year,
− Bank account: account number, name, currency,
balance, …
− Address book: name, address, telephone number, …
• In database applications, structures are called records.

Declaring a Structure:

The structure is declared by using the keyword struct


followed by structure name. Then the structure
members (variables) are defined with their
type and variable names inside the open and close
braces { and }.
Finally,the closed braces end with a semicolon denoted
as ; following the statement.
The above structure declaration is also called a
Structure Specifier.

2
7/31/2018

Records (structs) (continued)

• The general syntax of a struct is:

Example (1):
• Example:
struct Date { The “Date” structure
int day;
int month; has 3 members,
int year; day, month & year.
} ;

3
7/31/2018

Examples
• Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age; structure has 4 members
char Gender;
double CGA; of different types.
};

• Example:
struct StudentGrade{
char Name[15]; The “StudentGrade”
char Course[9]; structure has 5
int Lab[5];
int Homework[3]; members of
int Exam[2]; different array types.
}; 7

Declaration of a variable of struct type:


instance of a structure

This is similar to variable declaration. For


variable declaration, data type is defined followed
by variable name. For structure variable
declaration, the data type is the name of the
structure followed by the structure variable name.
<struct-type> <identifier_list>;
• Example:
StudentInfo Student1, Student2;
//Student1 and Student2 are variables of StudentInfo type.

4
7/31/2018

Example

Right at the end of the struct


definition, and before the ending
semicolon (;),
the optional field object_names
can be used to directly declare
objects of the structure type.
9

Accessing struct Members

• The syntax for accessing a struct


member is:

• The dot (.) is an operator, called the member


access operator

10

5
7/31/2018

11

Assigning Structures

• You can assign the contents of one structure


to another as long as both structures are
of the same type.
• The statement: student = newStudent;
copies the contents of newStudent into student

12

6
7/31/2018

Assignment (continued)
The assignment statement:

student = newStd;

is equivalent to the following statements:


student.firstName = newStd.firstName;
student.lastName = newStd.lastName;
student.courseGrade = newStd.courseGrade;
student.testScore = newStd.testScore;
student.programmingScore = newStd.programmingScore;
student.GPA = newStd.GPA;

13

Comparison (Relational Operators)

• Compare struct variables member-wise


• To compare the values of student and
newStudent:

14

7
7/31/2018

Input/Output

• No aggregate input/output operations on a


struct variable

• Data in a struct variable must be read one


member at a time

• The contents of a struct variable must be


written one member at a time

15

Input/Output (continued)

cout << newStudent.firstName


<< " " << newStudent.lastName
<< " " << newStudent.courseGrade
<< " " << newStudent.testScore
<< " " << newStudent.programmingScore
<< " " << newStudent.GPA << endl;

16

8
7/31/2018

Example
#include <iostream> int main()
using namespace std; {
Person p1;
struct Person cout << "Enter Full name: ";
{ cin.get(p1.name, 50);
char name[50]; cout << "Enter age: ";
cin >> p1.age;
int age;
cout << "Enter salary: ";
float salary; cin >> p1.salary;
};
cout << "\nDisplaying Information." <<
endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}
17

Example
#include <iostream> int main ()
#include <string> {
using namespace std; Student stu;
int i;
struct Student
cout << "Your name, please: ";
{ getline(cin, stu.name);
string name; cout << "\nYour id is: ";
int id; cin >> stu.id;
cout << "Enter your marks for three tests." << endl;
int mark[3]; for (i = 0; i < 3; i++)
}; {
cout << "Test " << i+1 << ": ";
cin >> stu.mark[i];
}
cout << endl;
cout << "Hello, " << stu.name << endl;
cout << "Your Student ID is " << stu.id << endl;
cout << "Your marks are: " << endl;
for (i = 0; i < 3; i++)
{ cout << "Test " << i+1 << ": " << stu.mark[i] << " " << endl;
}}

18

9
7/31/2018

Nesting structures
Structures can also be nested in such a way
that an element of a structure is itself another
structure:
struct movies_t {
string title;
int year; };

struct friends_t {
string name;
string email;
movies_t favorite_movie;
} charlie, maria;

19

Example:Nesting structures
#include<iostream.h>
struct distance
{
int feet;
float inches;
}
struct room
{
distance length; Void main ()
distance width; {
}; room dining;
dining.length.feet=13;
dining.length.inches=6.5;
dining.width.feet=10;
dining.width.inches=0.0;
float L=dining.length.feet+dining.length.inches/12;
float W=dining.width.feet+dining.width.inches/12;
cout<<”\n Dining room area is”<<L*W<<”Square feet”;
}
20

10
7/31/2018

Example :Array of structure


#include <iostream>
#include <string>
using namespace std;
main()
{
struct studentRecord{
string name; classA[1].name="Hala";
int number; classA[1].number=3456789;
int marks[5]; classA[1].marks[0]=88;
}; classA[1].marks[1]=79;
studentRecord classA[2]; classA[1].marks[2]=76;
classA[0].name="Ali"; classA[1].marks[3]=92;
classA[0].number=1234567; classA[1].marks[4]=83;
classA[0].marks[0]=97;
classA[0].marks[1]=88;
//printing the second students marks
classA[0].marks[2]=83;
classA[0].marks[3]=90; for(int i=0;i<5; i++) cout <<
classA[1].marks[i] << " "; }
classA[0].marks[4]=78;

21

struct Variables and Functions

• A struct variable can be passed as a


parameter by value or by reference

• A function can return a value of type struct

22

11
7/31/2018

Structs and functions


Passing Structures to Functions
• When a structure is used as an argument to a function, the
entire structure is passed by using the standard call-by-value
parameter passing mechanism.
• This, of course, means that any changes made to the contents
of the structure inside the function to which it is passed do not
affect the structure used as an argument.
• When using a structure as a parameter, remember that the type
of the argument must match the type of the parameter.

23

For example
The following program declares a structure called sample, and then
a function called f1( ) that takes a parameter of type sample

#include <iostream>
using namespace std;
arg.a = 1000;
struct sample {
int a;
arg.ch = 'X';
char ch; } ; f1(arg);
return 0; }
void f1(sample parm); void f1(sample parm)
int main() {
{ cout<<parm.a<<" "<<parm.ch<<
struct sample arg; "\n";
}

24

12
7/31/2018

Example

• struct fred
{ char x;
int y;
float z;
char s[10];
} mike;

• Here are examples of each member being passed to a function:


func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */
25

Example

• If you wish to pass the address of an individual


structure member, put the & operator before the
structure name.
• For example, to pass the address of the members of
the structure mike, write
func(&mike.x); //passes address of character x
func2(&mike.y); // passes address of integer y
func3(&mike.z); // passes address of float z
func4(mike.s); // passes address of string s
func(&mike.s[2]); // passes address of character s[2]

26

13
7/31/2018

Example
#include <iostream> int main()
struct Employee {
{ Employee joe = { 14, 32, 24.15 };
short id; Employee frank = { 15, 28, 18.27 };
int age; printInformation(joe);
double wage; cout << "\n";
}; printInformation(frank);
void printInformation(Employee employee) return 0;
{
}
cout << "ID: " << employee.id << "\n";
cout << "Age: " << employee.age << "\n";
cout << "Wage: " << employee.wage << "\n";
}

27

Structure Pointers

• You declare a structure pointer as you would any


other pointer variable, by putting an * in front of a
structure variable's name.
• For example, assuming the previously defined
structure inv_type, the following statement declares
inv_pointer to be a pointer to data of that type:
inv_type *inv_pointer;

28

14
7/31/2018

Structure Pointers

• To find the address of a structure variable, you must place the &
operator before the structure variable's name.
• For example, given the following fragment,
struct bal {
float balance;
char name[80];
} person;
bal *p; // declare a structure pointer
then
p = &person;
puts the address of person into the pointer p.

29

Structure Pointers

• The members of a structure can be accessed through


a pointer to the structure.
• However, you do not use the dot operator for this
purpose. Instead, you must use the –> operator.

• For example, this fragment accesses balance through p:


p->balance
The –> is called the arrow operator. It is formed by using the
minus sign followed by a greater than sign.

30

15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy