0% found this document useful (0 votes)
9 views59 pages

2 Lecture 1

The document provides an overview of records (structs) and pointers in C++. It explains how to define and access struct members, perform assignments, and compare struct variables. Additionally, it covers the use of pointers with structs, including declaration, dereferencing, and passing structs to functions.

Uploaded by

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

2 Lecture 1

The document provides an overview of records (structs) and pointers in C++. It explains how to define and access struct members, perform assignments, and compare struct variables. Additionally, it covers the use of pointers with structs, including declaration, dereferencing, and passing structs to functions.

Uploaded by

Omar Hamdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Records (structs) and

Pointers in C++
Records (structs)
• struct: collection of variables (members),
accessed by name
– Members may be of different types
• Syntax:

C++ Programming: Program Design Including Data Structures, Fifth Edition 2


Records (structs)
• A struct is a definition, not a declaration

C++ Programming: Program Design Including Data Structures, Fifth Edition 3


Accessing struct Members
• The syntax for accessing a struct
member is:

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


member access operator

C++ Programming: Program Design Including Data Structures, Fifth Edition 4


Accessing struct Members
• To initialize the members of newStudent:
newStudent.GPA = 0.0;
newStudent.firstName = "John";
newStudent.lastName = "Brown";

C++ Programming: Program Design Including Data Structures, Fifth Edition 5


Accessing struct Members

• More examples:
cin >> newStudent.firstName;
cin >> newStudent.testScore >>
newStudent.programmingScore;
score = (newStudent.testScore +
newStudent.programmingScore) / 2;

C++ Programming: Program Design Including Data Structures, Fifth Edition 6


Accessing struct Members

if (score >= 90)


newStudent.courseGrade = 'A';
else if (score >= 80)
newStudent.courseGrade = 'B';
else if (score >= 70)
newStudent.courseGrade = 'C';
else if (score >= 60)
newStudent.courseGrade = 'D';
else
newStudent.courseGrade = 'F';

C++ Programming: Program Design Including Data Structures, Fifth Edition 7


Assignment
• Value of one struct variable can be
assigned to another struct variable of
the same type using an assignment
statement
• The statement:
student = newStudent;
copies the contents of newStudent into
student

C++ Programming: Program Design Including Data Structures, Fifth Edition 8


Assignment
• The assignment statement:
student = newStudent;

is equivalent to the following statements:


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

C++ Programming: Program Design Including Data Structures, Fifth Edition 9


Comparison (Relational Operators)

• Compare struct variables member-wise


– No aggregate relational operations allowed
If(student>newStudent) is not allowed
• To compare the values of student and
newStudent:

C++ Programming: Program Design Including Data Structures, Fifth Edition 10


Input/Output
• No aggregate input/output operations on a struct
variable, it is not allowed to use cin>>newStudent
• 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

C++ Programming: Program Design Including Data Structures, Fifth Edition 11


#include <iostream>
#include <string>
using namespace std;
struct Records //global structure
{
int id;
char gender;
} ahmed, mohamed; //global variables of type struct

int main()
{

Records Said={1111,'m'}; // one way to initialize members


ahmed.id=2222;// another way using dot operator to access the
members
ahmed.gender='m';
mohamed=ahmed;
cout<<mohamed.id<<endl;
system ("pause");
return 0;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 12


#include <iostream>
#include <string>
using namespace std;
int main()
{
struct Records
{
int id;
char gender;
};
Records Said, ahmed, mohamed;
Said.id=2222;
ahmed.gender='m';
mohamed=Said;
cout<<mohamed.id<<endl;
system ("pause");
return 0;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 13


#include <iostream>
#include <string>
using namespace std;
int main()
{
struct Records //LOCAL STRUCTURE
{
int id;
char gender;
};
Records Said={5555, 'm'}, ahmed, mohamed; // one way to
inilize members
Said.id=2222; // using dot operator to access the
members
ahmed.gender='m';
mohamed=Said;
cout<<mohamed.id<<endl;
system ("pause");
return 0;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 14


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

C++ Programming: Program Design Including Data Structures, Fifth Edition 15


// Example
//Create a global structure with global variable, read
its members, and print it.
#include <iostream>
#include <iomanip>
using namespace std;
struct Time
{ // structure definition
int hour; // 0-23 (24-hour clock format)
int minute; // 0-59
int second; // 0-59

}; // end struct Time


Time dinnerTime;
void readTime(Time t);
void DisplayTime(Time t); // prototype

C++ Programming: Program Design Including Data Structures, Fifth Edition 16


int main()
{
cout << "Dinner will be held at ";
readTime( dinnerTime );
DisplayTime( dinnerTime );
cout << " universal time"<<endl;
system("pause");
return 0;
} // end main

void DisplayTime(Time t) // print time in universal-time


format
{
cout << setw( 2 ) << t.hour << ":"
<< setw( 2 ) << t.minute << ":"
<< setw( 2 ) << t.second;
}

void readTime(Time t) // print time in universal-time


format
{
dinnerTime.hour = 18; // set hour member of dinner Time
C++ Programming: Program Design Including Data Structures, Fifth Edition 17
dinnerTime.minute = 30; // set minute member of dinner
Arrays in structs
• Two key items are associated with a list:
– Values (elements)
– Length of the list
• Define a struct containing both items:

C++ Programming: Program Design Including Data Structures, Fifth Edition 18


Arrays in structs

C++ Programming: Program Design Including Data Structures, Fifth Edition 19


structs in Arrays

C++ Programming: Program Design Including Data Structures, Fifth Edition 20


structs in Arrays

C++ Programming: Program Design Including Data Structures, Fifth Edition 21


structs in Arrays

C++ Programming: Program Design Including Data Structures, Fifth Edition 22


• An example, to read from file and store in
structure

Smith Jack 60 45 98

Harry Hisk 45 40 78
Kay Jacob 35.5 23
45
Dos hed 23 20 35

Noa Tom 55 12 32

Joe Peni 57 49 78

Vin San 25.6 23


65.5
Jes Dan 24.3 12 78

Zi Lee 56 49 99
C++ Programming: Program Design Including Data Structures, Fifth Edition 23
Angi Dev 57 48 97
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
const int SIZE=15;
int i;
struct Records {
string firstname;
string secondname;
float test1mark;
float midtestmark;
float annualmark;
};
Records record[SIZE];

ifstream in("Data.txt");

if (!in){
cout<< "File can't be opened! " << endl;
system("PAUSE");
exit(1);
}
for (int i=0; i < SIZE; i++){
in >> record[i].firstname >> record[i].secondname
>>record[i].test1mark >> record[i].midtestmark >> record[i].annualmark ;
}
for (int i=0;i< SIZE;i++) {
cout << record[i].firstname<<" "<< record[i].secondname<<" "<<
record[i].test1mark<<" "<< record[i].midtestmark << " " << record[i].annualmark <<
" ";
cout<<endl;
}
system ("pause");
return 0;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 24


#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
void displayData(Person ); // Function declaration, variable name is not there, it is optional
int main()
{
Person p;
cout << "Enter Full name: ";
cin.get(p.name, 50); // cin>>p.name
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
// Function call with structure variable as an argument
displayData(p);
return 0;
}
void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
C++ Programming: Program Design Including Data Structures, Fifth Edition 25
#include<iostream.h>
#include<conio.h>

struct distance
{ int feet;
int inches;
};
void prnsum(distance l1, distance l2); // function prototype
void main()
{
clrscr();
distance length1, length2; // two structures of type distance declared
/* Read values for length1 */
cout<<"Enter length 1:\n";
cout<<"Feet: ";
cin>>length1.feet;
cout<<"\nInches: ";
cin>>length1.inches;

/* Read values for length2 */


cout<<"\n\nEnter length 2:\n";
cout<<"Feet: ";
cin>>length2.feet;
cout<<"\nInches: ";
cin>>length2.inches;
prnsum(length1, length2); // print sum of length1 and length2
getch();
} // end of main()
void prnsum(distance l1, distance l2)
{ distance l3; // new structure
l3.feet=l1.feet+l2.feet+(l1.inches+l2.inches)/12; // 1 feet=12 inches
l3.inches=(l1.inches+l2.inches)%12;
cout<<"\n\nTotal Feet: "<<l3.feet<<"\n";
cout<<"Total Inches: "<<l3.inches;
} C++ Programming: Program Design Including Data Structures, Fifth Edition 26
#include <iostream> //return structure from function
using namespace std;
struct student
{
char name[50];
int age;
};
// function prototype
struct student getInformation();

int main()
{
student s;
s = getInformation();
cout<<"\nDisplaying information\n";
cout<< s.name<<endl;
cout<<s.age;
system("pause");
return 0;
}
struct student getInformation()
{
student s1; //You can use s instead
of s1
cout<<"Enter name:"<<endl;
cin>> s1.name;

cout<<"Enter age:"<<endl;
cin>>s1.age;
return s1;
}
C++ Programming: Program Design Including Data Structures, Fifth Edition 27
structs within a struct

versus

C++ Programming: Program Design Including Data Structures, Fifth Edition 28


//Example

#include<iostream>
using namespace std;

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};

C++ Programming: Program Design Including Data Structures, Fifth Edition 29


int main()
{
int i;
Employee E;
cout << "\n\tEnter Employee Id : ";
cin >> E.Id;
cout << "\n\tEnter Employee Name : ";
cin >> E.Name;
cout << "\n\tEnter Employee Salary : ";
cin >> E.Salary;
cout << "\n\tEnter Employee House No : ";
cin >> E.Add.HouseNo;
cout << "\n\tEnter Employee House PinCode No : ";
cin >> E.Add.PinCode;
cout << "\nDetails of Employees";
cout << "\n\tEmployee Id : " << E.Id;
cout << "\n\tEmployee Name : " << E.Name;
cout << "\n\tEmployee Salary : " << E.Salary;
cout << "\n\tEmployee House No : " <<
E.Add.HouseNo;
cout << "\n\t House PinCode No : " <<
E.Add.PinCode;
system("pause");
return 0; Program Design Including Data Structures, Fifth Edition
C++ Programming: 30
}
Consider the following statements:
personalInfoType person;
personalInfoType classList[100];
nameType student;

Mark the following statements as valid or invalid. If a statement is invalid, explain why.

a) person.name.first = "William";
b) cout << person.name << endl;
c) classList[1] = person;
d) classList[20].pID = 0011100;
e) student = person.name;
f) cin >> student;

struct nameType { struct dateType { struct


string first; int month; personalInfoType {
string last; int day; nameType name;
}; int year; int pID;
}; dateType dob;
};

C++ Programming: Program Design Including Data Structures, Fifth Edition 31


Pointers

Chapter – 13
What is a pointer
• The pointer is a variable that holds an
address of another variable.

C++ Programming: Program Design Including Data Structures, Fifth Edition 33


Declaring Pointer Variables
• Syntax:

• Examples:
int *p;
char *ch;
• These statements are equivalent:
int *p;
int* p;
int * p;
C++ Programming: Program Design Including Data Structures, Fifth Edition 34
Declaring Pointer Variables
• In the statement:
int* p, q;
only p is the pointer variable, not q; here q
is an int variable
• To avoid confusion, attach the character *
to the variable name:
int *p, q;
int *p, *q;

C++ Programming: Program Design Including Data Structures, Fifth Edition 35


Address of Operator (&)
• The ampersand, &, is called the address of
operator
• The address of operator is a unary
operator that returns the address of its
operand

C++ Programming: Program Design Including Data Structures, Fifth Edition 36


Dereferencing Operator (*)
• When used as a unary operator, * is the
dereferencing operator or indirection operator
– Refers to object to which its operand points
• Example:

– To print the value of x, using p:

– To store a value in x, using p:

C++ Programming: Program Design Including Data Structures, Fifth Edition 37


Dereferencing Operator (*)

C++ Programming: Program Design Including Data Structures, Fifth Edition 38


Structs, and Pointer Variables
• You can declare pointers to other data types:

– student is an object of type studentType;


studentPtr is a pointer variable of type
studentType
C++ Programming: Program Design Including Data Structures, Fifth Edition 39
Structs, and Pointer Variables

• To store address of student in


studentPtr:
studentPtr = &student;

• To store 3.9 in component gpa of student:


(*studentPtr).gpa = 3.9;
– () used because dot operator has higher
precedence than dereferencing operator
– Alternative: use member access operator arrow
(->)
C++ Programming: Program Design Including Data Structures, Fifth Edition 40
Structs, and Pointer Variables
• The syntax for accessing a struct/class
member using the operator -> is:

• Thus,
(*studentPtr).gpa = 3.9;
is equivalent to:
studentPtr->gpa = 3.9;

C++ Programming: Program Design Including Data Structures, Fifth Edition 41


Initializing Pointer Variables
• C++ does not automatically initialize variables
• Pointer variables must be initialized if you do
not want them to point to anything
– Initialized using the constant value 0
• Called the null pointer
• Example: p = 0;
– Or, use the NULL named constant:
• p = NULL;
– The number 0 is the only number that can be
directly assigned to a pointer variable
C++ Programming: Program Design Including Data Structures, Fifth Edition 42
Dynamic Variables
• Dynamic variables: created during
execution
• C++ creates dynamic variables using
pointers
• Two operators, new and delete, to create
and destroy dynamic variables
– new and delete are reserved words

C++ Programming: Program Design Including Data Structures, Fifth Edition 43


Operator new
• new has two forms:

– where intExp is any expression evaluating


to a positive integer
• new allocates memory (a variable) of the
designated type and returns a pointer to it
– The address of the allocated memory
• The allocated memory is uninitialized
C++ Programming: Program Design Including Data Structures, Fifth Edition 44
Operator new

• The statement: p = &x;


– Stores address of x in p
• However, no new memory is allocated
• The statement: p = new int;
– Creates a variable during program execution
somewhere in memory, and stores the
address of the allocated memory in p
• To access allocated memory: *p

C++ Programming: Program Design Including Data Structures, Fifth Edition 45


Operator new

C++ Programming: Program Design Including Data Structures, Fifth Edition 46


Operator new
• new allocates memory space of a specific
type and returns the (starting) address of
the allocated memory space
• If new is unable to allocate the required
memory space, then it throws bad_alloc
exception
– If this exception is not handled, it terminates
the program with an error message

C++ Programming: Program Design Including Data Structures, Fifth Edition 47


Operator delete

C++ Programming: Program Design Including Data Structures, Fifth Edition 48


Operator delete

• To avoid memory leak, when a dynamic


variable is no longer needed, destroy it
– Deallocate its memory
• delete is used to destroy dynamic variables
• Syntax:

– Tip: to avoid dangling pointers, set variable to


NULL afterwards
C++ Programming: Program Design Including Data Structures, Fifth Edition 49
Operations on Pointer Variables
• Assignment: value of one pointer variable can
be assigned to another pointer of same type
• Relational operations: two pointer variables of
same type can be compared for equality, etc.
• Some limited arithmetic operations:
– Integer values can be added and subtracted from
a pointer variable
– Value of one pointer variable can be subtracted
from another pointer variable

C++ Programming: Program Design Including Data Structures, Fifth Edition 50


Operations on Pointer Variables
• Examples:
int *p, *q;
p = q;
– In this case, p == q will evaluate to true,
and p != q will evaluate to false
int *p
double *q;// double takes 8 bytes memory
– In this case, q++; increments value of q by 8,
and p = p + 2; increments value of p by 8

C++ Programming: Program Design Including Data Structures, Fifth Edition 51


Operations on Pointer Variables
• Pointer arithmetic can be very dangerous
– The program can accidentally access the
memory locations of other variables and
change their content without warning
• Some systems might terminate the program with
an appropriate error message
• Always exercise extra care when doing
pointer arithmetic

C++ Programming: Program Design Including Data Structures, Fifth Edition 52


Functions and Pointers
• A pointer variable can be passed as a
parameter either by value or by reference
• To make a pointer a reference parameter
in a function heading, use &:
void pointerParameters(int &p, double *q)
{
. . .
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 53


Pointers and Function Return Values

• A function can return a value of type


pointer:
int* testExp(...)
{
. . .
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 54


Given the first declaration statements,
mark the red statements as valid or invalid.
int x;
int *p;
int *q;

1. p = q;
2. *p = 56;
3. p = x;
4. *p = *q;
5. q = &x;
6. *p = q;
What is the output of the following C++
Program?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int *p;
int *q;
p = new int;
q = new int;
*p = 27;
*q = 35;
cout << *p << " " << *q << endl;
*q = *p;
*p = 73;
cout << *p << " " << *q << endl;
p = new int;
*p = 36;
q = p;
cout << *p << " " << *q << endl;
system("pause");
return 0;
}
// Function prototype
void swap(int*, int*);
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
C++ Programming: Program Design Including Data Structures, Fifth Edition 57
#include <iostream>
using namespace std;
// Function prototype
void swap(int*, int*);
int main()
{
int a = 1, b = 2;
int *p,*q;
p=&a;
q=&b;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(p,q);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

C++ Programming: Program Design Including Data Structures, Fifth Edition 58


What is the output of the following C++
code?
#include<iostream>
using namespace std;

void testMe(int p1, int p2)


{
p1 = 80;
p2 = p1;
}
int main(){
int i = 42, j = 80;
int *p1, *p2;
p1 = &i; p2 = &j;
testMe(*p1,*p2);
cout << *p1<<" - "<< *p2 <<endl;
system("pause");
return 0;
}

You might also like